|
14 | 14 | """ |
15 | 15 | from __future__ import annotations |
16 | 16 |
|
| 17 | +from collections import deque |
17 | 18 | from queue import Queue |
| 19 | +from timeit import timeit |
18 | 20 |
|
19 | 21 | G = { |
20 | 22 | "A": ["B", "C"], |
|
26 | 28 | } |
27 | 29 |
|
28 | 30 |
|
29 | | -def breadth_first_search(graph: dict, start: str) -> set[str]: |
| 31 | +def breadth_first_search(graph: dict, start: str) -> list[str]: |
30 | 32 | """ |
31 | | - >>> ''.join(sorted(breadth_first_search(G, 'A'))) |
| 33 | + Implementation of breadth first search using queue.Queue. |
| 34 | +
|
| 35 | + >>> ''.join(breadth_first_search(G, 'A')) |
32 | 36 | 'ABCDEF' |
33 | 37 | """ |
34 | 38 | explored = {start} |
| 39 | + result = [start] |
35 | 40 | queue: Queue = Queue() |
36 | 41 | queue.put(start) |
37 | 42 | while not queue.empty(): |
38 | 43 | v = queue.get() |
39 | 44 | for w in graph[v]: |
40 | 45 | if w not in explored: |
41 | 46 | explored.add(w) |
| 47 | + result.append(w) |
42 | 48 | queue.put(w) |
43 | | - return explored |
| 49 | + return result |
| 50 | + |
| 51 | + |
| 52 | +def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]: |
| 53 | + """ |
| 54 | + Implementation of breadth first search using collection.queue. |
| 55 | +
|
| 56 | + >>> ''.join(breadth_first_search_with_deque(G, 'A')) |
| 57 | + 'ABCDEF' |
| 58 | + """ |
| 59 | + visited = {start} |
| 60 | + result = [start] |
| 61 | + queue = deque([start]) |
| 62 | + while queue: |
| 63 | + v = queue.popleft() |
| 64 | + for child in graph[v]: |
| 65 | + if child not in visited: |
| 66 | + visited.add(child) |
| 67 | + result.append(child) |
| 68 | + queue.append(child) |
| 69 | + return result |
| 70 | + |
| 71 | + |
| 72 | +def benchmark_function(name: str) -> None: |
| 73 | + setup = f"from __main__ import G, {name}" |
| 74 | + number = 10000 |
| 75 | + res = timeit(f"{name}(G, 'A')", setup=setup, number=number) |
| 76 | + print(f"{name:<35} finished {number} runs in {res:.5f} seconds") |
44 | 77 |
|
45 | 78 |
|
46 | 79 | if __name__ == "__main__": |
47 | 80 | import doctest |
48 | 81 |
|
49 | 82 | doctest.testmod() |
50 | | - print(breadth_first_search(G, "A")) |
| 83 | + |
| 84 | + benchmark_function("breadth_first_search") |
| 85 | + benchmark_function("breadth_first_search_with_deque") |
| 86 | + # breadth_first_search finished 10000 runs in 0.20999 seconds |
| 87 | + # breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds |
0 commit comments