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

Wolfgang Maier wolfgang.maier at biologie.uni-freiburg.de
Fri Jan 6 15:06:58 EST 2017


On 1/6/2017 15:04, Peter Otten wrote:
> 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()?
>

How about:

def stopmin (iterable, key, stop):
     def take_until ():
         for e in iterable:
             yield e
             if key(e) <= stop:
                 break
     return min(take_until(), key=key)

?



More information about the Python-list mailing list