Fu Fundamentals of Pr Programming (Py Python)
Recursion
Ali Taheri Sharif University of Technology
Spring 2019
Recursion Ali Taheri Sharif University of Technology Spring 2019 - - PowerPoint PPT Presentation
Fu Fundamentals of Pr Programming (Py Python) Recursion Ali Taheri Sharif University of Technology Spring 2019 Outline 1. Recursive Functions 2. Example: Fibonacci 3. Memoization 4. Example: Binomial Coefficient 5. Example: Towers of
Spring 2019
2
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
π! = π β π β 1 ! ππ π > 0 1 ππ’βππ π₯βππ‘π
the base cases
3
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
πΊππ π = ππ π = 0 1 ππ π = 1 πΊππ π β 1 + πΊππ π β 2 ππ’βππ π₯ππ‘π
4
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
def fib(n): if n == 0: # Base Case return 0 if n == 1: # Base Case return 1 return fib(n-1) + fib(n-2) # Recursion Step
π π = π π β 1 + π β 1 π β 1 π 0 = π π = 1
5
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
def bin(n,k): if k == 0 or k == n: # Base Cases return 1 return bin(n-1,k) + bin(n-1,k-1) # Recursion Step
with the help of the third peg under some constraints
6
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
three pegs
7
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
8
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
def hanoi(n, source, target, third): if n == 1: # Base case (we have only one disk) print('Moving disk %d from %s to %s' % (n, source, target)) else: # Recursive Step # Move n-1 disk from source to third hanoi(n - 1, source, third, target) # Move nth disk from source to target print('Moving disk %d from %s to %s' % (n, source, target)) # Move n-1 disk from third to target hanoi(n - 1, third, target, source)
9
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
Assume a table π having following value in cell (π, π):
π(π, π) = π π = 1
π=1 π
π(π β 1, π) π > 1
Write a function to calculate π(π, π) recursively.
We have a game board having β rows and π columns. Having a marble in row 1 and column π (cell (1, π)). In each phase, we can move the marble to the next row of current column or
Write a recursive function to compute the number of ways we can move the marble to cell (π, π).
10
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
memo = {} # Partial results def fib(n): if n == 0: # Base Case return 0 if n == 1: # Base Case return 1 if n in memo: # Return the result if return memo[n] # it has already computed memo[n] = fib(n-1) + fib(n-2) # Save the result return memo[n]
product of two matrices
large π
11
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
12
ALI TAHERI - FUNDAMENTALS OF PROGRAMMING [PYTHON] Spring 2019
def exp(A, n): if n == 0: # Base Case return [[1, 0], [0, 1]] temp = exp(A, n // 2) # A**(n/2) prod = mat_prod(temp, temp) # A**n if n % 2 == 0: return prod else: return mat_prod(prod, A)