""" min2_max2.py -- V.1.1, Sep 25 2006, by maffi leonardo. To mimic min and max functions of Python 2.5. Note: it supports only the first argument and the key, they don't accept many arguments. Some tests: >>> min2([1,2,-1]) -1 >>> min2([1]) 1 >>> min2([1,2,0.1]) 0.10000000000000001 >>> min2([]) Traceback (most recent call last): ... ValueError: min2() arg is an empty sequence. >>> min2([], key=lambda x:x) Traceback (most recent call last): ... ValueError: min2() arg is an empty sequence. >>> min2([(1, "b"), (2,"a")], key=lambda (x,y):y) (2, 'a') >>> min2([(1, "b"), (2,"a")], key=lambda (x,y):x) (1, 'b') >>> def it(): ... for el in [1,2,3]: yield el ... >>> list(it()) [1, 2, 3] >>> min2(it()) 1 >>> max2([1,2,-1]) 2 >>> max2([2]) 2 >>> max2([1,2.1,0.1]) 2.1000000000000001 >>> max2([]) Traceback (most recent call last): ... ValueError: max2() arg is an empty sequence. >>> max2([], key=lambda x:x) Traceback (most recent call last): ... ValueError: max2() arg is an empty sequence. >>> max2([(1, "b"), (2,"a")], key=lambda (x,y):y) (1, 'b') >>> max2([(1, "b"), (2,"a")], key=lambda (x,y):x) (2, 'a') """ def min2(elements, key=None): """min2(elements, key=None): given an iterable and a key function like the key of sort, it returns the minimum element. This function mimics the min of Python 2.5""" if key is None: try: min_el = min(elements) return min_el except ValueError: raise ValueError, "min2() arg is an empty sequence." elements = iter(elements) try: min_el = elements.next() except StopIteration: raise ValueError, "min2() arg is an empty sequence." min_val = key(min_el) for el in elements: curr_val = key(el) if curr_val < min_val: min_el = el min_val = curr_val return min_el def max2(elements, key=None): """max2(elements, key=None): given an iterable and a key function like the key of sort, it returns the maximum element. This function mimics the max of Python 2.5.""" if key is None: try: max_el = max(elements) return max_el except ValueError: raise ValueError, "max2() arg is an empty sequence." elements = iter(elements) try: max_el = elements.next() except StopIteration: raise ValueError, "max2() arg is an empty sequence." max_val = key(max_el) for el in elements: curr_val = key(el) if curr_val > max_val: max_el = el max_val = curr_val return max_el def _test(): import doctest doctest.testmod() if __name__ == "__main__": _test() print "min2, max2 tests finished."