Lambda Expression deriving maximum calculated value

Advertisements

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?

>Solution :

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)

Leave a Reply Cancel reply