Functional Python Programming

(Wang) #1
Chapter 3

We've used one important for loop in addition to recursion. This allows us to easily
handle numbers that have as many as 1,000 factors. This number is at least as large


as 2 1,000, a number with 300 digits. Since the for variable, i, is not used outside
the indented body of the loop, the stateful nature of the i variable won't lead to
confusion if we make any changes to the body of the loop.


In effect, we've done tail-call optimization, the recursive calls that count from 3 to x.
The for loop saves us from deeply recursive calls that test every single number in
the range.


The other two for loops exist merely to consume the results of a recursive function
that is iterable.


In a recursive generator function, be careful of the return statement.
Do not use the following command line:
return recursive_iter(args)
It returns only a generator object; it doesn't evaluate the function to
return the generated values. Use either of the following:
for result in recursive_iter(args):
yield result
OR yield from recursive_iter(args)

As an alternative, the following command is a more purely recursive version:


def pfactorsr(x):
def factor_n(x, n):
if n*n > x:
yield x
return
if x % n == 0:
yield n
if x//n > 1:
yield from factor_n(x//n, n)
else:
yield from factor_n(x, n+2)
if x % 2 == 0:
yield 2
if x//2 > 1:
yield from pfactorsr(x//2)
return
yield from factor_n(x, 3)

Free download pdf