From 762afc086f065f1d8fe1afcde8c8ad3fa46898a7 Mon Sep 17 00:00:00 2001 From: Andrey Date: Fri, 28 Oct 2022 23:27:39 +0300 Subject: [PATCH] Update breadth_first_search_2.py (#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 --- graphs/breadth_first_search_2.py | 45 +++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 4 deletions(-) diff --git a/graphs/breadth_first_search_2.py b/graphs/breadth_first_search_2.py index 2f060a90d..a0b92b90b 100644 --- a/graphs/breadth_first_search_2.py +++ b/graphs/breadth_first_search_2.py @@ -14,7 +14,9 @@ while Q is non-empty: """ from __future__ import annotations +from collections import deque from queue import Queue +from timeit import timeit G = { "A": ["B", "C"], @@ -26,12 +28,15 @@ G = { } -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(): @@ -39,12 +44,44 @@ def breadth_first_search(graph: dict, start: str) -> set[str]: 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