Add lesson 7: Graphs: BFS and DFS

Mira Kovac 8 months ago
parent 0977b28ef1 commit 9ee5823d230bf5f1afd750c45e152b7edd4c8061
3 changed files with 43 additions and 0 deletions
+19-0lessons/07-graphs-bfs-and-dfs/README.md ADDED
@@ -0,0 +1,19 @@
1+# Lesson 7: Graphs: BFS and DFS
2+
3+Graphs: BFS and DFS 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/7](https://glibcode.net/courses/algorithms/lessons/7)
6+
7+## Files
8+
9+- `graphs.py`: shortest path in an unweighted graph with BFS
10+
11+## Run it
12+
13+```sh
14+python3 graphs.py
15+```
16+
17+## Exercises
18+
19+See [exercises.md](exercises.md). Ask in the forum once you've tried.
+5-0lessons/07-graphs-bfs-and-dfs/exercises.md ADDED
@@ -0,0 +1,5 @@
1+# Exercises: lesson 7
2+
3+1. Look up one function or command the example uses in the official documentation. Note one option you didn't know.
4+2. Find one thing in `graphs.py` you could name better and rename it everywhere.
5+3. Combine this lesson with the previous one: use something from both in a small program of your own.
+19-0lessons/07-graphs-bfs-and-dfs/graphs.py ADDED
@@ -0,0 +1,19 @@
1+from collections import deque
2+
3+
4+def shortest_path(graph, start, goal):
5+ queue = deque([[start]])
6+ seen = {start}
7+ while queue:
8+ path = queue.popleft()
9+ if path[-1] == goal:
10+ return path
11+ for nxt in graph[path[-1]]:
12+ if nxt not in seen:
13+ seen.add(nxt)
14+ queue.append(path + [nxt])
15+ return None
16+
17+
18+metro = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
19+print(shortest_path(metro, "A", "F")) # ['A', 'B', 'D', 'F']