Commit ca9835cd by Ben Glocker

### cleared notebooks 00 and 02

This diff is collapsed.
This diff is collapsed.
 %% Cell type:markdown id: tags: # CO202 - Algorithms 2 %% 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) ``` %%%% Output: stream 55 54.9 µs ± 10.4 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) %% 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) ``` %%%% Output: stream 55 4.13 µs ± 285 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %% 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) ``` %%%% Output: execute_result (0, 0.6281491025812429) %%%% Output: display_data %% Cell type:code id: tags: ``` python ``` ... ...
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!