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

Paul Rubin no.email at nospam.invalid
Sun Jan 8 05:02:02 EST 2017


Paul Rubin <no.email at nospam.invalid> writes:
> Doesn't look that way to me:
>     >>> minabs([5,3,1,2,4])
>     1

There's a different problem though:

    >>> minabs([1,2,3,0])
    1

I think Python's version of iterators is actually buggy and at least the
first element of the rest of the sequence should be preserved.  There
are ways to fake it but they're too messy for something like this.  It
should be the default and might have been a good change for Python 3.

    def minabs2(xs):
        def z():
            for x in xs:
                yield x
                if x==0: break
        return min((abs(x),x) for x in z())[1]


seems to work, but is ugly.  Maybe there's something better.



More information about the Python-list mailing list