Skip to Content
Functional Python Programming - Second Edition
book

Functional Python Programming - Second Edition

by Steven F. Lott
April 2018
Intermediate to advanced content levelIntermediate to advanced
408 pages
10h 42m
English
Packt Publishing
Content preview from Functional Python Programming - Second Edition

Leaving recursion in place

In some cases, the recursive definition is actually optimal. Some recursions involve a divide and conquer strategy that minimizes the work. One example of this is the exponentiation by the squaring algorithm. We can state it formally as follows:

We've broken the process into three cases, easily written in Python as a recursion. Look at the following command snippet:

def fastexp(a: float, n: int) -> float:
    if n == 0:         return 1
    elif n % 2 == 1:         return a*fastexp(a, n-1)
    else:
        t= fastexp(a, n//2)
        return t*t

This function has three cases. The base case, the fastexp(a, 0) method is defined as having a value of 1. The ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Functional Python Programming - Third Edition

Functional Python Programming - Third Edition

Steven F. Lott

Publisher Resources

ISBN: 9781788627061Supplemental Content