The Itertools Module
We'll get the next value from the iterator. If it passes the test, that's our value.
Otherwise, we'll evaluate this function recursively to search for a value that passes
the test.
We'll provide a source iterable and a comparison function as follows:
source = zip(count(0, .1), (.1*c for c in count()))
neq = lambda x, y: abs(x-y) > 1.0E-12
When we evaluate the until(neq, source) method, we find the result is as follows:
(92.799999999999, 92.80000000000001)
After 928 iterations, the sum of the error bits has accumulated to 10 −^12. Neither value
has an exact binary representation.
The count() function is close to the Python recursion limit. We'd
need to rewrite our until() function to use tail-call optimization to
locate counts with larger accumulated errors.
The smallest detectible difference can be computed as follows:
until(lambda x, y: x != y, source)
(0.6, 0.6000000000000001)
After just six steps, the count(0, 0.1) method has accumulated a measurable error
of 10 −^16. Not a large error, but within 1000 steps, it will be considerably larger.
Reiterating a cycle with cycle()
The cycle() function repeats a sequence of values. We can imagine using it to solve
silly fizz-buzz problems.
Visit http://rosettacode.org/wiki/FizzBuzz for a comprehensive set of
solutions to a fairly trivial programming problem. Also see https://projecteuler.
net/problem=1 for an interesting variation on this theme.
We can use the cycle() function to emit sequences of True and False values
as follows:
m3= (i == 0 for i in cycle(range(3)))
m5= (i == 0 for i in cycle(range(5)))