01_01_what-is-recursion-lesson-notes-optional-download_Recursion - What is Recursion
01_01_what-is-recursion-lesson-notes-optional-download_Recursion - What is Recursion
Recursion
What is Recursion?
Solving a coding problem with functions involves breaking down the
problem into smaller problems. When these smaller problems are
variations of the larger problem (also know as self-similar), then recursion
can be used. For example, the mathematical function factorial is self-
similar. Five factorial (5!) is calculated as 5 * 4 * 3 * 2 * 1. Mouse over
the image below to see that 5! is really just 5 * 4!, and 4! is really just 4 *
3! and so on.
def factorial(n):
"""Calculate factorial recursively"""
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Code Visualizer
The base case is the most important part of a recursive function. Without
it, the function will never stop calling itself. Like an infinite loop, Python
will stop the program with an error.
def factorial(n):
"""Recursion without a base case"""
return n * factorial(n - 1)
print(factorial(5))
Code Visualizer
Always start with the base case when creating a recursive function. Each
time the function is called recursively, the program should get one step
closer to the base case.
challenge
Modify the base case so that factorial(0) does not result in an error.
Test your new base case with a negative number.
Solution
The factorial operation only works with positive integers. So the base
case should be if n <= 0:.
Code Visualizer
Fibonacci Sequence
Fibonacci Number
A Fibonacci number is a number in which the current number is the sum
of the previous two Fibonacci numbers.
Fibonacci Sequence
def fibonacci(n):
"""Calculate Fibonacci numbers"""
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
print(fibonacci(3))
Code Visualizer
challenge
Fibonacci Sequence
Fibonacci numbers are most often talked about as a sequence. The code
below adds the functionality of printing a Fibonacci sequence of
predetermined length.
def fibonacci(n):
"""Calculate Fibonacci numbers"""
if n <= 1:
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
fibonacci_length = 10
for num in range(fibonacci_length):
print(fibonacci(num))
Code Visualizer
challenge
The code written above is terribly inefficient. Each time through the loop,
Python is calculating the same Fibonacci numbers again and again. When
num is 1, Python calculates the Fibonacci numbers for 0 and 1. When num is
2, Python is calculating the Fibonacci numbers for 0, 1, and 2. Once num
becomes large enough, it becomes too much work for Python to have to
recalculate these large numbers over and over again. There is a more
efficient way to do this by using a data structure called a dictionary. The
idea is to store previously calculated Fibonacci numbers in the dictionary.
So instead of recalculating the same numbers again and again, you can get
these numbers from the dictionary. If a Fibonacci number is not in the
dictionary, then calculate it and add it to the dictionary. Data structures
are a bit beyond the scope of these lessons, but here is the code of a more
efficient way to calculate and print the Fibonacci sequence. Copy and
paste the code below into the IDE if you want to run it.
fibcache = {} #dictionary of Fibonacci numbers
def fibonacci(n):
"""Check to see if a Fibonacci number has been calculated (in the dictionary).
def _fibonacci(n):
"""Calculate Fibonacci number"""
if n <= 1:
return n
else:
fib = fibonacci(n-1) + fibonacci(n-2)
return fib
fibonacci_length = 90
for num in range(fibonacci_length):
print(fibonacci(num))