Firefox about:srcdoc
Cheatsheets / Learn Recursion with Python
Recursion: Python
Stack Over�ow Error in Recursive Function
A recursive function that is called with an input that def myfunction(n):
requires too many iterations will cause the call stack to
if n == 0:
get too large, resulting in a stack over�ow error. In
these cases, it is more appropriate to use an iterative return n
solution. A recursive solution is only suited for a else:
problem that does not exceed a certain number of
return myfunction(n-1)
recursive calls.
For example, myfunction() below throws a stack
over�ow error when an input of 1000 is used. myfunction(1000) #results in stack
overflow error
Fibonacci Sequence
A Fibonacci sequence is a mathematical series of Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8,
numbers such that each number is the sum of the two
13, 21, ...
preceding numbers, starting from 0 and 1.
Call Stack Construction in While Loop
A call stack with execution contexts can be constructed
using a while loop, a list to represent the call
stack and a dictionary to represent the execution
contexts. This is useful to mimic the role of a call stack
inside a recursive function.
Binary Search Tree
In Python, a binary search tree is a recursive data 5
structure that makes sorted lists easier to search.
/ \
Binary search trees:
• Reference two children at most per tree node. / \
• The “left” child of the tree must contain a value 3 8
lesser than its parent.
/ \ / \
• The “right” child of the tree must contain a
value greater than it’s parent.
2 4 7 9
1 of 6 6/17/23, 10:39
Firefox about:srcdoc
Recursion and Nested Lists
A nested list can be traversed and �attened using a def flatten(mylist):
recursive function. The base case evaluates an element
flatlist = []
in the list. If it is not another list, the single element is
appended to a �at list. The recursive step calls the for element in mylist:
recursive function with the nested list element as input. if type(element) == list:
flatlist += flatten(element)
else:
flatlist += element
return flatlist
print(flatten(['a', ['b', ['c', ['d']],
'e'], 'f']))
# returns ['a', 'b', 'c', 'd', 'e', 'f']
Fibonacci Recursion
Computing the value of a Fibonacci number can be def fibonacci(n):
implemented using recursion. Given an input of index N,
if n <= 1:
the recursive function has two base cases – when the
index is zero or 1. The recursive function returns the return n
sum of the index minus 1 and the index minus 2. else:
The Big-O runtime of the Fibonacci function is O(2^N).
return fibonacci(n-1) +
fibonacci(n-2)
2 of 6 6/17/23, 10:39
Firefox about:srcdoc
Modeling Recursion as Call Stack
One can model recursion as a call stack with def countdown(value):
execution contexts using a while loop and a call_stack = []
Python list . When the base case is reached, print
while value > 0 :
out the call stack list in a LIFO (last in �rst out)
manner until the call stack is empty. call_stack.append({"input":value})
Using another while loop, iterate through the call print("Call Stack:",call_stack)
stack list . Pop the last item o� the list and add it to a value -= 1
variable to store the accumulative result.
print("Base Case Reached")
Print the result.
while len(call_stack) != 0:
print("Popping {} from call
stack".format(call_stack.pop()))
print("Call Stack:",call_stack)
countdown(4)
'''
Call Stack: [{'input': 4}]
Call Stack: [{'input': 4}, {'input': 3}]
Call Stack: [{'input': 4}, {'input': 3},
{'input': 2}]
Call Stack: [{'input': 4}, {'input': 3},
{'input': 2}, {'input': 1}]
Base Case Reached
Popping {'input': 1} from call stack
Call Stack: [{'input': 4}, {'input': 3},
{'input': 2}]
Popping {'input': 2} from call stack
Call Stack: [{'input': 4}, {'input': 3}]
Popping {'input': 3} from call stack
Call Stack: [{'input': 4}]
Popping {'input': 4} from call stack
Call Stack: []
'''
Recursion in Python
In Python, a recursive function accepts an argument def countdown(value):
and includes a condition to check whether it matches
if value <= 0: #base case
the base case. A recursive function has:
• Base Case - a condition that evaluates the print("done")
current input to stop the recursion from else:
continuing.
print(value)
• Recursive Step - one or more calls to the
recursive function to bring the input closer to countdown(value-1) #recursive case
the base case.
3 of 6 6/17/23, 10:39
Firefox about:srcdoc
Build a Binary Search Tree
To build a binary search tree as a recursive algorithm def build_bst(my_list):
do the following:
if len(my_list) == 0:
BASE CASE:
return "No Child"
If the list is empty, return "No Child" to show that there
RECURSIVE STEP:
middle_index = len(my_list) // 2
1. Find the middle index of the list.
2. Create a tree node with the value of the middle middle_value
index. = my_list[middle_index]
3. Assign the tree node's left child to a recursive call w
4. Assign the tree node's right child to a recursive call
print("Middle index:
5. Return the tree node.
{0}".format(middle_index))
print("Middle value:
{0}".format(middle_value))
tree_node = {"data": middle_value}
tree_node["left_child"] =
build_bst(my_list[ : middle_index])
tree_node["right_child"] =
build_bst(my_list[middle_index + 1 : ])
return tree_node
sorted_list = [12, 13, 14, 15, 16]
binary_search_tree =
build_bst(sorted_list)
print(binary_search_tree)
Recursive Depth of Binary Search Tree
A binary search tree is a data structure that builds a def depth(tree):
sorted input list into two subtrees. The left child of the
if not tree:
subtree contains a value that is less than the root of the
tree. The right child of the subtree contains a value that return 0
is greater than the root of the tree. left_depth = depth(tree["left_child"])
A recursive function can be written to determine the
right_depth =
depth of this tree.
depth(tree["right_child"])
return max(left_depth, right_depth) + 1
4 of 6 6/17/23, 10:39
Firefox about:srcdoc
Sum Digits with Recursion
Summing the digits of a number can be done def sum_digits(n):
recursively. For example:
if n <= 9:
552 = 5 + 5 + 2 = 12
return n
last_digit = n % 10
return sum_digits(n // 10) + last_digit
sum_digits(552) #returns 12
Palindrome in Recursion
A palindrome is a word that can be read the same both def is_palindrome(str):
ways - forward and backward. For example, abba is a
if len(str) < 2:
palindrome and abc is not.
The solution to determine if a word is a palindrome can return True
be implemented as a recursive function. if str[0] != str[-1]:
return False
return is_palindrome(str[1:-1])
Fibonacci Iterative Function
A Fibonacci sequence is made up adding two previous def fibonacci(n):
numbers beginning with 0 and 1. For example:
if n < 0:
0, 1, 1, 2, 3, 5, 8, 13, ...
raise ValueError("Input 0 or greater
A function to compute the value of an index in the only!")
Fibonacci sequence, fibonacci(index) can be
fiblist = [0, 1]
written as an iterative function.
for i in range(2,n+1):
fiblist.append(fiblist[i-1] +
fiblist[i-2])
return fiblist[n]
Recursive Multiplication
The multiplication of two numbers can be solved def multiplication(num1, num2):
recursively as follows:
if num1 == 0 or num2 == 0:
Base case: Check for any number that is equal to zero.
return
Recursive step: Return the first number plus a recursive c 0
return num1 + multiplication(num1, num2
- 1)
5 of 6 6/17/23, 10:39
Firefox about:srcdoc
Iterative Function for Factorials
To compute the factorial of a number, multiply all the def factorial(n):
numbers sequentially from 1 to the number.
answer = 1
An example of an iterative function to compute a
factorial is given below. while n != 0:
answer *= n
n -= 1
return answer
Recursively Find Minimum in List
We can use recursion to �nd the element with the def find_min(my_list):
minimum value in a list, as shown in the code below.
if len(my_list) == 0:
return None
if len(my_list) == 1:
return my_list[0]
#compare the first 2 elements
temp = my_list[0] if my_list[0] <
my_list[1] else my_list[1]
my_list[1] = temp
return find_min(my_list[1:])
print(find_min([]) == None)
print(find_min([42, 17, 2, -1, 67]) ==
-1)
Print Share
6 of 6 6/17/23, 10:39