views:

139

answers:

2

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

+14  A: 
def get_max(f, s):
  return max(s, key=f)
Alex Martelli
+1 hard to do better than plain old `max()`
gnibbler
True! But I didn´t know you could pass this magic key argument. Thanks!
Manuel
Reference: http://docs.python.org/library/functions.html#max
S.Lott
A: 
def get_max(f, s):
    l = [f(i) for i in s]
    l.sort()

    return l[-1]
inspectorG4dget
You forgot to call `sort`. Also, your solution is `O(n log n)` when the linear solution is quite obvious. The best solution is to use `max` with the `key` argument provided.
Mike Graham