Implement the argmin function from math, in a form that makes use of generator expressions in 2.4.
1 2 3 4 5 6 7 8 9
def argmin(sequence, fn=None): """Two usage patterns: argmin([s0, s1, ...], fn) argmin([(fn(s0), s0), (fn(s1, s1), ...]) Both return the si with lowest fn(si)""" if fn is None: return min(sequence) else: return min((fn(e), e) for e in sequence)
Often you want to find the element of a set that is "best" in some way. In math, this is usually notated with argmin (or argmax):
best = argmine in S f(e)
where f is a function that gives a score, and low score is best. Python syntax doesn't allow subscripts like this, but we can come up with two protocols that are not too ugly. Examples:
If we have sequence = ['one', 'to', 'three'], then
argmin(sequence, len) ==> 'to' ## because 'to' has smallest len.
argmin((len(x), x) for x in sequence) ==> 'to' ## alternate protocol
Note that with generator expressions this is efficient (doesn't build up a large intermediate list) and not too hard to read.