Functional Python Programming

(Wang) #1
Chapter 8

This function can be thought of as the primitive basis for a function like
enumerate(). We can define the enumerate() function in terms of zip() and
count() functions, as follows:


enumerate = lambda x, start=0: zip(count(start),x)


The enumerate() function behaves as if it's a zip() function that uses the count()
function to generate the values associated with some iterator.


Consequently, the following two commands are equivalent to each other:


zip(count(), some_iterator)


enumerate(some_iterator)


Both will emit a sequence of numbers of two tuples paired with items from
the iterator.


The zip() function is made slightly simpler with the use of the count() function,
as shown in the following command:


zip(count(1,3), some_iterator)


This will provide values of 1, 4, 7, 10, and so on, as the identifiers for each value from
the enumerator. This is a challenge because enumerate doesn't provide a way to
change the step.


The following command describes the enumerate() function:


((1+3*e, x) for e,x in enumerate(a))


The count() function permits non-integer values. We can use
something like the count(0.5, 0.1) method to provide floating-
point values. This will accumulate a substantial error if the increment
value doesn't have an exact representation. It's generally better to
use the (0.5+x*.1 for x in count()) method to assure that
representation errors don't accumulate.

Here's a way to examine the accumulating error. We'll define a function, which
will evaluate items from an iterator until some condition is met. Here's how we can
define the until() function:


def until(terminate, iterator):


i = next(iterator)


if terminate(*i): return i


return until(terminate, iterator)

Free download pdf