Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more pythonic way of finding element in list that maximizes a function

OK, I have this simple function that finds the element of the list that maximizes the value of another positive function.

def get_max(f, s):
    # f is a function and s is an iterable

    best = None
    best_value = -1

    for element in s:
        this_value = f(element)
        if this_value > best_value:
            best = element
            best_value = this_value
    return best

But I find it very long for the simple work it does. In fact, it reminds me of Java (brrrr). Can anyone show me a more pythonic and clean way of doing this?

Thanks!
Manuel

like image 296
Manuel Araoz Avatar asked Dec 07 '22 04:12

Manuel Araoz


1 Answers

def get_max(f, s):
  return max(s, key=f)
like image 139
Alex Martelli Avatar answered Jan 21 '23 09:01

Alex Martelli