Search a sequence for its minimum and stop as soon as the lowest possible value is found
Peter Otten
__peter__ at web.de
Sun Jan 8 06:24:04 EST 2017
Paul Rubin wrote:
> Paul Rubin <no.email at nospam.invalid> writes:
>> seems to work, but is ugly. Maybe there's something better.
>
> def minabs2(xs):
> def z():
> for x in xs:
> yield abs(x), x
> if x==0: break
> return min(z())[1]
>
> is the same thing but a little bit nicer.
Yes, that's another variant of the decorate/undecorate approach combined
with Wolfgang's local take_until(). The generalized form that cannot rely on
the sequence items being orderable would be
firstitem = operator.itemgetter(0)
def stopmin_paul(items, *, key, stop):
def take_until():
for item in items:
k = key(item)
yield k, item
if k <= stop:
break
return min(take_until(), key=firstitem)[1]
More information about the Python-list
mailing list