Recursion: The process of solving a problem by reducing it to smaller versions of itself is called recursion.
Recursive definition: a definition in which something is defined in terms of smaller version of itself.
Recursive algorithm: an algorithm that finds a solution to a given problem by reducing the problem to smaller versions of itself
Infinite recursion: never stops
# Recursively print countdown from 10-1 and blast off!
# Run it as a script
import os
import time
def countDown(n):
os.system('clear')
if n == 0:
print('Blast Off!')
time.sleep(1)
os.system('clear')
else:
print(n)
time.sleep(1)
countDown(n-1) # tail recursion
#print(n)
countDown(10)
fib(0) = 0 - base case 1 fib(1) = 1 - base case 2 fib(n) = fib(n-1) + fib(n-2) for n >= 2 - general case
# In Python:
#count = 0
def fib(n):
global count
#count += 1
if n <= 1:
return n
f = fib(n-1) + fib(n-2)
return f
fib(10)
#print(count)
#assert fib(8) == 21
#assert fib(10) == 55
from IPython.display import IFrame
src = """
http://pythontutor.com/iframe-embed.html#code=%23%20In%20Python%3A%0Adef%20fib%28n%29%3A%0A%20%20%20%20if%20n%20%3C%3D%201%3A%0A%20%20%20%20%20%20%20%20return%20n%0A%20%20%20%20f%20%3D%20fib%28n-1%29%20%2B%20fib%28n-2%29%0A%20%20%20%20return%20f%0A%20%20%20%20%0Aprint%28fib%284%29%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false
"""
IFrame(src, width=900, height=300)
0! = 1 - base case n! = n.(n-1)! for n >= 1 - general case
Write a recursive fact(n) function that takes a positive integer n and returns its factorial.
Here are some test cases that the fact(n) should pass: assert fact(5) == 120 assert fact(10) == 3628800 assert fact(100) == math.factorial(100)
Write a recursive function -- gcd(a, b) -- that finds the greatest common divisor of two given positive integers, a and b.
Here are some test cases that gcd(a, b) should pass: assert gcd(2, 100) == 2 assert gcd(50, 10) == 10 assert gcd(125, 75) == 25
Write a program that simulates the steps required to solve the "Tower of Hanoii" puzzle for some disks n.
Recursive algorithm
If there are 1 or more disks to move:
def moveDisks(n, src, helper, dst):
if n > 0:
moveDisks(n-1, src, dst, helper)
print('Move disk #{} from {} to {}'.format(n, src, dst))
moveDisks(n-1, helper, src, dst)
moveDisks(3, 'needle1', 'needle2', 'needle3')