Recursion
Recursion
Recursion: Python
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.
1 of 6 6/17/23, 10:39
Firefox about:srcdoc
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
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
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))
return tree_node
4 of 6 6/17/23, 10:39
Firefox about:srcdoc
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])
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
print(find_min([]) == None)
print(find_min([42, 17, 2, -1, 67]) ==
-1)
Print Share
6 of 6 6/17/23, 10:39