Compare commits
2 Commits
2d521ad349
...
6a8a19655a
Author | SHA1 | Date | |
---|---|---|---|
|
6a8a19655a | ||
|
15eeaec1f3 |
16
README.md
16
README.md
|
@ -1,3 +1,15 @@
|
|||
# mit_606_dp
|
||||
# MIT 6.006 Introduction to Algorithms
|
||||
|
||||
Implementations of some dynamic programing example outlined in the MIT 6.006 "Introduction to Algorithms"
|
||||
Implementations of some dynamic programing example outlined in the available material on youtube.
|
||||
|
||||
- 2011
|
||||
- [Dynamic Programming I: Fibonacci, Shortest Paths](https://www.youtube.com/watch?v=OQ5jsbhAv_M)
|
||||
- [Dynamic Programming II: Text Justification, Blackjack](https://www.youtube.com/watch?v=ENyox7kNKeY)
|
||||
- [Dynamic Programming III: Parenthesization, Edit Distance, Knapsack](https://www.youtube.com/watch?v=ocZMDMZwhCY)
|
||||
- [Dynamic Programming IV: Guitar Fingering, Tetris, Super Mario Bros.](https://www.youtube.com/watch?v=tp4_UXaVyx8)
|
||||
|
||||
- 2020
|
||||
- [Part 1: SRTBOT, Fib, DAGs, Bowling](https://www.youtube.com/watch?v=r4-cftqTcdI)
|
||||
- [Part 2: LCS, LIS, Coins](https://www.youtube.com/watch?v=KLBCUx1is2c)
|
||||
- [Part 3: APSP, Parens, Piano](https://www.youtube.com/watch?v=TDo3r5M1LNo)
|
||||
- [Part 4: Rods, Subset Sum, Pseudopolynomial](https://www.youtube.com/watch?v=i9OAOk0CUQE)
|
||||
|
|
26
fibonacci.py
Normal file
26
fibonacci.py
Normal file
|
@ -0,0 +1,26 @@
|
|||
def fibonacci(n: int):
|
||||
"""Return the n-th Fibonacci number."""
|
||||
|
||||
memo: dict[int, int] = {}
|
||||
"""The memoization register."""
|
||||
|
||||
def dp(i: int):
|
||||
"""Recursive subproblem: return memoized i-th Fibonacci number."""
|
||||
|
||||
# check if memoized yet
|
||||
f = memo.get(i, None)
|
||||
if f is not None:
|
||||
return f
|
||||
|
||||
# compute actual value, making "free" recursive calls
|
||||
f = 2 if i <= 2 else dp(i-1) + dp(i-2)
|
||||
|
||||
# set the memoization register
|
||||
memo[i] = f
|
||||
|
||||
return f
|
||||
|
||||
return dp(n)
|
||||
|
||||
|
||||
print(f"The 9th Fibonacci number is: {fibonacci(9)}")
|
Loading…
Reference in New Issue
Block a user