Search a sequence for its minimum and stop as soon as the lowest possible value is found
Peter Otten
__peter__ at web.de
Sat Jan 7 06:44:05 EST 2017
Wolfgang Maier wrote:
> 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)
>> ?
Clean and simple -- if it could be tweaked to invoke key() just once per
item it would be perfect.
More information about the Python-list
mailing list