Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Lambda Expression deriving maximum calculated value

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading