Skip to content
GitLab
Menu
Projects
Groups
Snippets
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
Ben Glocker
algo202
Commits
8f48c8b2
Commit
8f48c8b2
authored
Jan 30, 2018
by
Ben Glocker
Browse files
added dynamic programming notebook
parent
9474c0be
Changes
3
Expand all
Show whitespace changes
Inline
Side-by-side
00-Introduction.ipynb
View file @
8f48c8b2
This diff is collapsed.
Click to expand it.
01-Divide-and-Conquer.ipynb
View file @
8f48c8b2
This diff is collapsed.
Click to expand it.
02-Dynamic-Programming.ipynb
0 → 100644
View file @
8f48c8b2
%% 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
```
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment