Lambda Expression deriving maximum calculated value

Question:

I have this problem where I have a collection of values and I’m trying to identify the greatest distance from other value. I can achieve this easily with a for loop and about 4 lines of code, but I’m trying to see if I can achieve the same effect with a lambda expression.

I can simplify the problem with the following code:

def distance(x: int, y: int) -> int:
    return abs(x-y)


my_pos = 54
others = [12, -3, 83, -155, 54]

result = max(others, key=lambda target: distance(my_pos, target))

print(result)

This code correctly tells me which of my values is furthest away, -155, but my desired value is actually the result of this distance, 209. Is there an adjustment I can make to keep this as a one-liner?

Asked By: SSHunter49

||

Answers:

You should not use key if you actually want the results of the function, you can use a comprehension.

key is only used to "specif[y] a function of one argument that is used to extract a comparison key" (from docs).

def distance(x: int, y: int) -> int:
    return abs(x-y)

my_pos = 54
others = [12, -3, 83, -155, 54]

result = max(distance(my_pos, target) for target in others)

print(result)
Answered By: ljmc

A generator expression is a simpler approach than a lambda expression here:

result = max(abs(my_pos - target) for target in others)
Answered By: Michael Butscher

If you wanna try out lambda expression with one-liner:

print((lambda n, l: max(abs(n - i) for i in l))(my_pos, others))
Answered By: Freda Xin

You could still maintain lambda:

def distance(pos: int, values: list) -> int:
    return max(map(lambda x: abs(pos-x), values))
    
my_pos = 54
others = [12, -3, 83, -155, 54]

result = distance(my_pos, others)
print(result)
Answered By: Jamiu Shaibu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.