Recursion basics

In [1]:
# This is an example of a function with two arguments

def sumTwo(x, y):
    return x + y
print(sumTwo(1, 2))
3
In [7]:
# You can have functions that call functions

def sumThree(x, y, z):
    return x + sumTwo(y, z)
print(sumThree(1, 2, 3))
6
In [8]:
# You can have functions that call functions that call functions

def sumFour(a, b, c, d):
    return a + sumThree(b, c, d)
print(sumFour(1, 2, 3, 4))
10
In [2]:
# Wouldn't it be great if we could have a single function do the hard work of adding a list?
# (Note: it's possible to do this with a loop, but let's say we want to do this without for now)
In [5]:
# NOTE: if there is a board, do this on the board
# 0 + recSumList([1, 2, 3])
# 1 + recSumList([2, 3])
# 2 + recSumList([3])
# 3
# -> 3 + 2 + 1 + 0
# -> 6

# Also do without base case
In [3]:
# In addition to being able to call other functions, a function can call itself!
# A function calling itself is "recursion"
# NOTE: bewarned. As with while loops, these can go on forever
# YOU MUST HAVE A BASE CASE!!

def recSumList(x):
    if len(x) == 1:
        return x[0]
    return x[0] + recSumList(x[1:])

recSumList([0, 1, 2, 3])
Out[3]:
6
In [7]:
# This works in general!

recSumList([1, 10, 2, 4])
Out[7]:
17
In [6]:
# Sum the numbers in a list with a loops
# As we have said, there are many way to do the same thing
# Many of the functions you have written so far can be written with recursion

def sumList(x):
    s = 0
    for y in x:
        s += y
    return s

sumList([1, 10, 2, 4])
Out[6]:
17
In [12]:
# Definition of factorial: n! = n * (n - 1) * (n - 2) * ... * 3 * 2 * 1
# Also, 1! = 1
# How can you turn this into a recursion?
# Recursive case: n! = n * (n - 1)!
# Base case: 1! = 1

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

print(factorial(1))
print(factorial(2))
print(factorial(3))
print(factorial(4))
1
2
6
24
In [18]:
# This is the fibonacci sequence
# f(0) = 1
# f(1) = 1
# f(2) = f(1) + f(0)
# f(n) = f(n - 1) + f(n - 2)

# How can we write this with code?

def fib(n):
    if n == 0 or n == 1:
        return 1
    return fib(n - 1) + fib(n - 2)

print(fib(1))
print(fib(2))
print(fib(3))
print(fib(4))
print(fib(15))
1
2
3
5
987
In [9]:
# The steps of writing a recursive function:
# 1. Given a large instance of a problem, how can you break the problem down into smaller pieces?
#    (ignore the base-case)
# 2. What instances of the problem do you know the answer to? (base case)
# 3. Put them together
In [11]:
# Sum list example
# recSumList([x[0], x[1], x[2], ..., x[n]]) = x[0] + sumList([x[1], x[2], ..., x[n]])
# recSumList([x[0]]) = x[0]

def recSumList(x):
    if len(x) == 1:
        return x[0]
    return x[0] + recSumList(x[1:])
recSumList([1, 2, 3, 4])
Out[11]:
10