Skip to content

Commit 762afc0

Browse files
Cjkjvfnbypre-commit-ci[bot]cclauss
authored
Update breadth_first_search_2.py (TheAlgorithms#7765)
* Cleanup the BFS * Add both functions and timeit * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Add performace results as comment * Update breadth_first_search_2.py Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <[email protected]>
1 parent fe5819c commit 762afc0

File tree

1 file changed

+41
-4
lines changed

1 file changed

+41
-4
lines changed

graphs/breadth_first_search_2.py

+41-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
"""
1515
from __future__ import annotations
1616

17+
from collections import deque
1718
from queue import Queue
19+
from timeit import timeit
1820

1921
G = {
2022
"A": ["B", "C"],
@@ -26,25 +28,60 @@
2628
}
2729

2830

29-
def breadth_first_search(graph: dict, start: str) -> set[str]:
31+
def breadth_first_search(graph: dict, start: str) -> list[str]:
3032
"""
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'))
3236
'ABCDEF'
3337
"""
3438
explored = {start}
39+
result = [start]
3540
queue: Queue = Queue()
3641
queue.put(start)
3742
while not queue.empty():
3843
v = queue.get()
3944
for w in graph[v]:
4045
if w not in explored:
4146
explored.add(w)
47+
result.append(w)
4248
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")
4477

4578

4679
if __name__ == "__main__":
4780
import doctest
4881

4982
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

Comments
 (0)