Dynamic Programming
Source
Table of Contents
%%html
<center><iframe width="560" height="315" src="https://www.youtube.com/embed/t4MSwiqfLaY"
frameborder="0" allowfullscreen></iframe></center>
print ('{c}\n'.format(c="Hello class"))
def foo(str):
print(str)
foo('Hello class')
def foo_recursion(str):
print('{s}\n'.format(s=str))
foo_recursion(str)
# Do not run. It falls into infinite loop.
#foo_recursion('Hello Class')
# base line
def foo_recursion_correct(n):
if n <= 0:
return
else:
print('Hi! \n')
foo_recursion_correct(n-1)
foo_recursion_correct(4)
n = 5
m = 1
for i in range(n):
m = m*(i+1)
print (m)
def fac(n):
if n == 1:
return 1
else:
return n*fac(n-1)
# recursive
fac(5)
it works, Is it good?
Benefit?
$\quad \implies$ DP $\simeq$ recursion + memorization
%%html
<center><iframe width="560" height="315"src="https://www.youtube.com/embed/OQ5jsbhAv_M"
frameborder="0" allowfullscreen></iframe></center>
# naive Fibonacci
def fib(n):
if n <= 2:
return 1
else:
return fib(n-1) + fib(n-2)
fib(10)
# Memorized DP Fibonacci
def mfib(n):
global memo
if memo[n-1] != 0:
return memo[n-1]
elif n <= 2:
return 1
else:
memo[n-1] = mfib(n-1) + mfib(n-2)
return memo[n-1]
import numpy as np
n = 10
memo = np.zeros(n)
mfib(n)
memo
n = 30
%timeit fib(30)
memo = np.zeros(n)
%timeit mfib(30)
You are climbing a stair case. Each time you can either make 1 step, 2 steps, or 3 steps. How many distinct ways can you climb if the stairs has $n = 30$ steps?
import numpy as np
def stair(n):
global memo
if memo[n] != 0:
m = memo[n]
elif n == 1:
m = 1
elif n == 2:
m = 2
elif n == 3:
m = 4
else:
m = stair(n-1) + stair(n-2) + stair(n-3)
memo[n] = m
return m
n = 5
global memo
memo = np.zeros(n+1)
stair(n)
print(memo)
%%html
<center><iframe src="https://www.youtube.com/embed/M6OGAI_4N_w?rel=0"
width="420" height="315" frameborder="0" allowfullscreen></iframe></center>
%%html
<center><iframe src="https://www.youtube.com/embed/wY4lW0t8QZg?rel=0"
width="420" height="315" frameborder="0" allowfullscreen></iframe></center>
%%javascript
$.getScript('https://kmahelona.github.io/ipython_notebook_goodies/ipython_notebook_toc.js')