Commit 8f48c8b2 by Ben Glocker

### added dynamic programming notebook

parent 9474c0be
This diff is collapsed.
This diff is collapsed.
 %% Cell type:markdown id: tags: # CO202 - Software Engineering - Algorithms %% Cell type:markdown id: tags: ## Tutorial on Dynamic Programming: Fibonacci %% Cell type:markdown id: tags: ### Naive Divide-and-Conquer Approach %% Cell type:code id: tags: ``` python def naive_fib(n): if n == 0: return 0 elif n == 1: return 1 else: return naive_fib(n-1) + naive_fib(n-2) print(naive_fib(10)) %timeit naive_fib(10) ``` %% Cell type:markdown id: tags: ### Bottom-up Dynamic Programming Approach %% Cell type:code id: tags: ``` python def dp_fib(n): if n == 0: return 0 f = [0]*(n+1) f[0] = 0 f[1] = 1 for i in range(2,n+1): f[i] = f[i-1] + f[i-2] return f[n] print(dp_fib(10)) %timeit dp_fib(10) ``` %% Cell type:markdown id: tags: ### Comparison %% Cell type:markdown id: tags: #### Timer %% Cell type:code id: tags: ``` python import time def time_f(f): before = time.clock() f() after = time.clock() return after - before ``` %% Cell type:markdown id: tags: #### Test data %% Cell type:code id: tags: ``` python data = range(1,20) #data = range(1,30) #data = range(1,1000,10) #data = range(1,10000,100) #data = range(1,100000,1000) ``` %% Cell type:markdown id: tags: #### Running Divide-and-Conquer %% Cell type:code id: tags: ``` python tdc = [] for i in data: tdc.append(time_f(lambda: naive_fib(i))) ``` %% Cell type:markdown id: tags: #### Running Dynamic Programming %% Cell type:code id: tags: ``` python tdp = [] for i in data: tdp.append(time_f(lambda: dp_fib(i))) ``` %% Cell type:markdown id: tags: #### Plot DC vs DP %% Cell type:code id: tags: ``` python %matplotlib inline from matplotlib import pyplot as plt plt.scatter(data, tdc, c='red') plt.scatter(data, tdp, c='blue') plt.xlabel('n') plt.ylabel('time (/s)') plt.xlim(0) plt.ylim(0) ``` %% Cell type:code id: tags: ``` python ```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment