Add lesson 3: Hash maps
3 changed files with 38 additions and 0 deletions
lessons/03-hash-maps/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 3: Hash maps | |
| 2 | + | |
| 3 | +This lesson covers hash maps. You'll read a short explanation, try three small exercises and finish with a quiz. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/3](https://glibcode.net/courses/algorithms/lessons/3) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `hash_maps.py`: two-sum and counting with dictionaries | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 hash_maps.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/03-hash-maps/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 3 | |
| 2 | + | |
| 3 | +1. Rewrite the main part so it runs twice with two different inputs, without copying the code. | |
| 4 | +2. What happens with an empty input? Change the code so it handles that case with a clear message. | |
| 5 | +3. Add a comment above each block explaining what it does, in your own words. | |
lessons/03-hash-maps/hash_maps.py ADDED
| @@ -0,0 +1,14 @@ | ||
| 1 | +from collections import Counter | |
| 2 | + | |
| 3 | + | |
| 4 | +def two_sum(nums, target): | |
| 5 | + seen = {} | |
| 6 | + for i, n in enumerate(nums): | |
| 7 | + if target - n in seen: | |
| 8 | + return seen[target - n], i | |
| 9 | + seen[n] = i | |
| 10 | + return None | |
| 11 | + | |
| 12 | + | |
| 13 | +print(two_sum([2, 7, 11, 15], 9)) # (0, 1) | |
| 14 | +print(Counter("mississippi").most_common(2)) | |