Skip to content

Update breadth_first_search_2.py #7765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 41 additions & 4 deletions graphs/breadth_first_search_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
"""
from __future__ import annotations

from collections import deque
from queue import Queue
from timeit import timeit

G = {
"A": ["B", "C"],
Expand All @@ -26,25 +28,60 @@
}


def breadth_first_search(graph: dict, start: str) -> set[str]:
def breadth_first_search(graph: dict, start: str) -> list[str]:
"""
>>> ''.join(sorted(breadth_first_search(G, 'A')))
Implementation of breadth first search using queue.Queue.

>>> ''.join(breadth_first_search(G, 'A'))
'ABCDEF'
"""
explored = {start}
result = [start]
queue: Queue = Queue()
queue.put(start)
while not queue.empty():
v = queue.get()
for w in graph[v]:
if w not in explored:
explored.add(w)
result.append(w)
queue.put(w)
return explored
return result


def breadth_first_search_with_deque(graph: dict, start: str) -> list[str]:
"""
Implementation of breadth first search using collection.queue.

>>> ''.join(breadth_first_search_with_deque(G, 'A'))
'ABCDEF'
"""
visited = {start}
result = [start]
queue = deque([start])
while queue:
v = queue.popleft()
for child in graph[v]:
if child not in visited:
visited.add(child)
result.append(child)
queue.append(child)
return result


def benchmark_function(name: str) -> None:
setup = f"from __main__ import G, {name}"
number = 10000
res = timeit(f"{name}(G, 'A')", setup=setup, number=number)
print(f"{name:<35} finished {number} runs in {res:.5f} seconds")


if __name__ == "__main__":
import doctest

doctest.testmod()
print(breadth_first_search(G, "A"))

benchmark_function("breadth_first_search")
benchmark_function("breadth_first_search_with_deque")
# breadth_first_search finished 10000 runs in 0.20999 seconds
# breadth_first_search_with_deque finished 10000 runs in 0.01421 seconds