# This is an example of a function with two arguments
def sumTwo(x, y):
return x + y
print(sumTwo(1, 2))
3
# You can have functions that call functions
def sumThree(x, y, z):
return x + sumTwo(y, z)
print(sumThree(1, 2, 3))
6
# 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
# 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)
# 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 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])
6
# This works in general!
recSumList([1, 10, 2, 4])
17
# 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])
17
# 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
# 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
# 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
# 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])
10