Add lesson 4: Stacks and queues
3 changed files with 45 additions and 0 deletions
lessons/04-stacks-and-queues/README.md ADDED
| @@ -0,0 +1,19 @@ | ||
| 1 | +# Lesson 4: Stacks and queues | |
| 2 | + | |
| 3 | +In this lesson you'll work through stacks and queues step by step, with short exercises after each idea. | |
| 4 | + | |
| 5 | +Full lesson: [https://glibcode.net/courses/algorithms/lessons/4](https://glibcode.net/courses/algorithms/lessons/4) | |
| 6 | + | |
| 7 | +## Files | |
| 8 | + | |
| 9 | +- `stacks_queues.py`: balanced brackets with a stack, a queue with deque | |
| 10 | + | |
| 11 | +## Run it | |
| 12 | + | |
| 13 | +```sh | |
| 14 | +python3 stacks_queues.py | |
| 15 | +``` | |
| 16 | + | |
| 17 | +## Exercises | |
| 18 | + | |
| 19 | +See [exercises.md](exercises.md). Ask in the forum once you've tried. | |
lessons/04-stacks-and-queues/exercises.md ADDED
| @@ -0,0 +1,5 @@ | ||
| 1 | +# Exercises: lesson 4 | |
| 2 | + | |
| 3 | +1. Explain the example to someone who hasn't taken the course. Which part was hardest to explain? | |
| 4 | +2. Combine this lesson with the previous one: use something from both in a small program of your own. | |
| 5 | +3. What happens with an empty input? Change the code so it handles that case with a clear message. | |
lessons/04-stacks-and-queues/stacks_queues.py ADDED
| @@ -0,0 +1,21 @@ | ||
| 1 | +from collections import deque | |
| 2 | + | |
| 3 | +PAIRS = {")": "(", "]": "[", "}": "{"} | |
| 4 | + | |
| 5 | + | |
| 6 | +def balanced(text): | |
| 7 | + stack = [] | |
| 8 | + for ch in text: | |
| 9 | + if ch in "([{": | |
| 10 | + stack.append(ch) | |
| 11 | + elif ch in PAIRS: | |
| 12 | + if not stack or stack.pop() != PAIRS[ch]: | |
| 13 | + return False | |
| 14 | + return not stack | |
| 15 | + | |
| 16 | + | |
| 17 | +print(balanced("{[()()]}"), balanced("(]")) | |
| 18 | + | |
| 19 | +queue = deque(["first", "second"]) | |
| 20 | +queue.append("third") | |
| 21 | +print(queue.popleft(), list(queue)) | |