Skip to content Skip to sidebar Skip to footer

Python Finding Minimum Values Of Functions Of List Items, But Returning The List Item

Sorry, it's a bit hard to explain my question in a title, but basically, I have a list of positions, and each position can be passed through a function to get a number that gives y

Solution 1:

Python is pretty cool :D:

min(positions, key=posfunc)

From built-in documentation:

>>> help(min)
min(...)
    min(iterable[, key=func]) -> value
    min(a, b, c, ...[, key=func]) -> value

    With a single iterable argument, return its smallest item.
    With two or more arguments, return the smallest argument.

And lambda's are worth mentioning here:

min(positions, key=lambda x: x[0]**2 - x[1])

Is roughly the same, but more readable I think, if you aren't using posfunc elsewhere.


Solution 2:

you can basically use the min() function

pos = [(234, 4365), (234, 22346), (2342, 674)]

def posfunc(pos):
    x,y = pos
    return x**2-y

min(pos, key=posfunc)

Post a Comment for "Python Finding Minimum Values Of Functions Of List Items, But Returning The List Item"