Search a sequence for its minimum and stop as soon as the lowest possible value is found
jussi.piitulainen at helsinki.fi
Sun Jan 8 02:01:08 EST 2017
Pablo Lucena writes:
> How about using the second usage of builtin iter()?
> In : iter?
> iter(iterable) -> iterator
> iter(callable, sentinel) -> iterator
Nice to learn about that. But it has the same problem as
> In : numbers
> Out: [1, 9, 8, 11, 22, 4, 0, 3, 5, 6]
> # create iterator over the numbers to make callable simple
> # you may pre-sort or do w/e as needed of course
> In : numbers_it = iter(numbers)
> # callable passed into iter - you may customize this
> # using functools.partial if need to add function arguments
> In : def grab_until():
> ...: return next(numbers_it)
> # here 0 is the 'sentinel' ('int()' would work as well as you have
> # the iterator produced by iter() here stops as soon as sentinel value
> # is encountered
> In : list(iter(grab_until, 0))
> Out: [1, 9, 8, 11, 22, 4]
You get the same with numbers = [1, 9, 8, 11, 22, 4], where 0 does not
occur. How do you then tell which it was?
I think both itertools.takewhile(-, -) and iter(-, -) should have an
option to include the sentinel in their output. Then they could be used
in situations like this.
[The discussion with Rustom about Haskell's lazy evaluation is not
related to this, as far as I can see, so I just snipped it from here.]
More information about the Python-list