Welcome, guest | Sign In | My Account | Store | Cart

Adds a key= argument to min and max modeled after that of list.sort and sorted.

These will become obsolete in Python 2.5. when the builtin min() and max() functions gain the key= argument.

Python, 17 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class _minmax(object):
    def __init__(self, func):
        self.func = func
    def __call__(self, *seq, **kwargs):
        key = kwargs.pop('key', None)
        if kwargs:
            raise TypeError("only 'key' accepted as a "
                            "keyword argument")
        if key is None:
            return self.func(*seq)
        if len(seq) == 1:
            seq, = seq
        return self.func((key(item), i, item)
                         for i, item in enumerate(seq))[-1]

min = _minmax(min)
max = _minmax(max)

Raymond Hettinger previously posted a similar recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355690

This implementation augments the functionality of Raymond Hettinger's recipe, supporting both argument forms accepted by the current builtin min and max: a single sequence and *args list. As will be true in Python 2.5, 'key' is only accepted as a keyword argument (never as a positional one). <pre>py> min('ab', 'c') 'ab' py> min('ab', 'c', key=len) 'c' py> d = dict(a=2, b=1) py> max(d) 'b' py> max(d, key=d.__getitem__) 'a'</pre>

Created by Steven Bethard on Fri, 25 Feb 2005 (PSF)
Python recipes (4591)
Steven Bethard's recipes (7)

Required Modules

  • (none specified)

Other Information and Tasks