I discovered today that Python's min and max functions accept a
key keyword that allows you to pass a function that returns a value to minimise. This can be used to return elements out of tuples or attributes from objects. For example:
>>> min ((2,1), (3,0), (4,1), key = lambda x:x[1])
(3, 0)
This functionality turns out to be really useful (like when you're merging bounding rectangles). Unfortunately it's not available in Python 2.4, but it is possible to reimplement:
import sys
if sys.version_info[:2] < (2, 5):
print >> sys.stderr, "INFO: using reimplementations of min/max()"
def _min_max_mapper (func, args, kwargs):
if kwargs.has_key ('key'):
# reimplement
key = kwargs['key']
if len (args) == 1 and type (args[0]) is list:
values = args[0]
else:
values = args
mappedvalues = [ key (arg) for arg in values ]
value = func (mappedvalues)
return values[mappedvalues.index (value)]
else:
return func (*args)
_realmin = min
_realmax = max
min = lambda *a, **b: _min_max_mapper (_realmin, a, b)
max = lambda *a, **b: _min_max_mapper (_realmax, a, b)Importing this will implement Python 2.5 min/max semantics in earlier versions on Python.