Add lesson 8: Dynamic programming
3 changed files with 43 additions and 0 deletions
lessons/08-dynamic-programming/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 8: Dynamic programming | |
| 2 | + | |
| 3 | +Dynamic programming comes up in almost every real Python project. We start with the why, then write code together. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/8](https://glibcode.net/courses/algorithms/lessons/8) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `dynamic_programming.py`: coin change, top-down and bottom-up | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 dynamic_programming.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/08-dynamic-programming/dynamic_programming.py ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +from functools import lru_cache | |
| 2 | + | |
| 3 | + | |
| 4 | +def min_coins(coins, amount): | |
| 5 | + best = [0] + [float("inf")] * amount | |
| 6 | + for a in range(1, amount + 1): | |
| 7 | + for c in coins: | |
| 8 | + if c <= a: | |
| 9 | + best[a] = min(best[a], best[a - c] + 1) | |
| 10 | + return best[amount] if best[amount] != float("inf") else -1 | |
| 11 | + | |
| 12 | + | |
| 13 | +@lru_cache(maxsize=None) | |
| 14 | +def fib(n): | |
| 15 | + return n if n < 2 else fib(n - 1) + fib(n - 2) | |
| 16 | + | |
| 17 | + | |
| 18 | +print(min_coins((1, 5, 10, 25), 63)) # 6 | |
| 19 | +print(fib(80)) | |
lessons/08-dynamic-programming/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 8 | |
| 2 | + | |
| 3 | +1. Find one thing in `dynamic_programming.py` you could name better and rename it everywhere. | |
| 4 | +2. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
| 5 | +3. Time yourself: rewrite the example from memory in 10 minutes, then diff it against the original. | |