Search a sequence for its minimum and stop as soon as the lowest possible value is found

Peter Otten __peter__ at web.de
Fri Jan 6 09:04:02 EST 2017


Example: you are looking for the minimum absolute value in a series of 
integers. As soon as you encounter the first 0 it's unnecessary extra work 
to check the remaining values, but the builtin min() will continue.

The solution is a minimum function that allows the user to specify a stop 
value:

>>> from itertools import count, chain
>>> stopmin(chain(reversed(range(10)), count()), key=abs, stop=0)
0

How would you implement stopmin()?

Currently I raise an exception in the key function:

class Stop(Exception):
    pass

def stopmin(items, key, stop):
    """
    >>> def g():
    ...     for i in reversed(range(10)):
    ...         print(10*i)
    ...         yield str(i)
    >>> stopmin(g(), key=int, stop=5)
    90
    80
    70
    60
    50
    '5'
    """
    def key2(value):
        result = key(value)
        if result <= stop:
            raise Stop(value)
        return result
    try:
        return min(items, key=key2)
    except Stop as stop:
        return stop.args[0]




More information about the Python-list mailing list