Functional Python Programming

(Wang) #1

Functions, Iterators, and Generators


We defined an internal recursive function, factor_n(), to test factors, n, in the range
3 ≤≤nx. If the candidate factor, n, is outside the range, then x is prime. Otherwise,


we'll see if n is a factor of x. If so, we'll yield n and all factors of


x
n. If n is not a factor,
we'll evaluate the function recursively using n+2. This recursion to test each value
of (nn++2, 22 + ,n+++ 222 ,...) can be optimized into a for loop, as shown in the
previous example.


The outer function handles some edge cases. As with other prime-related processing,
we handle 2 as a special case. For even numbers, we'll yield 2 and then evaluate
pfactorsr() recursively for x÷2. All other prime factors must be odd numbers greater
than or equal to 3. We'll evaluate the factors_n() function starting with 3 to test these
other candidate prime factors.


The purely recursive function can only locate prime
factors of numbers up to about 4,000,000. Above this,
Python's recursion limit will be reached.

Exploring the limitations of generators


We noted that there are some limitations of generator expressions and
generator functions. The limitations can be observed by executing the
following command snippet:





from ch02_ex4 import *
pfactorsl( 1560 )
<generator object pfactorsl at 0x1007b74b0>
list(pfactorsl(1560))
[2, 2, 2, 3, 5, 13]
len(pfactorsl(1560))
Traceback (most recent call last):
File "", line 1, in
TypeError: object of type 'generator' has no len()





In the first example, we saw that generator functions are not strict. They're lazy,
and don't have a proper value until we consume the generator functions. This isn't a
limitation, per se; this is the whole reason that generator expressions fit with functional
programming in Python.


In the second example, we materialized a list object from the generator function.
This is handy for seeing the output and writing unit test cases.


In the third example, we saw one limitation of generator functions: there's no len().

Free download pdf