Add lesson 1: Big-O in plain words
3 changed files with 45 additions and 0 deletions
lessons/01-big-o-in-plain-words/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 1: Big-O in plain words | |
| 2 | + | |
| 3 | +In this lesson you'll work through big-O in plain words step by step, with short exercises after each idea. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/1](https://glibcode.net/courses/algorithms/lessons/1) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `big_o.py`: timing O(n) against O(n^2) on growing inputs | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 big_o.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/01-big-o-in-plain-words/big_o.py ADDED
| @@ -0,0 +1,21 @@ | ||
| 1 | +import time | |
| 2 | + | |
| 3 | + | |
| 4 | +def has_duplicate_slow(items): # O(n^2) | |
| 5 | + for i in range(len(items)): | |
| 6 | + for j in range(i + 1, len(items)): | |
| 7 | + if items[i] == items[j]: | |
| 8 | + return True | |
| 9 | + return False | |
| 10 | + | |
| 11 | + | |
| 12 | +def has_duplicate_fast(items): # O(n) | |
| 13 | + return len(set(items)) != len(items) | |
| 14 | + | |
| 15 | + | |
| 16 | +for n in (1_000, 2_000, 4_000): | |
| 17 | + data = list(range(n)) | |
| 18 | + for fn in (has_duplicate_slow, has_duplicate_fast): | |
| 19 | + start = time.perf_counter() | |
| 20 | + fn(data) | |
| 21 | + print(f"{fn.__name__:<20} n={n:<6} {time.perf_counter() - start:.4f}s") | |
lessons/01-big-o-in-plain-words/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 1 | |
| 2 | + | |
| 3 | +1. What happens with an empty input? Change the code so it handles that case with a clear message. | |
| 4 | +2. Look up one function or command the example uses in the official documentation. Note one option you didn't know. | |
| 5 | +3. Break the example on purpose: delete a bracket or misspell a name. Read the error message. Which line does it point to? | |