From 33a56b2e2042ba45bd63f94b43f1f4c2f6e213a8 Mon Sep 17 00:00:00 2001 From: onyx-and-iris Date: Fri, 12 Jan 2024 12:19:51 +0000 Subject: [PATCH] upd bfs, dfs on rooted tree add readme --- chapter7/README.md | 5 +++++ chapter7/bfs_dirtrav.py | 24 ++++++++++++++---------- chapter7/dfs_dirtrav.py | 25 +++++++++++++++++++++++++ 3 files changed, 44 insertions(+), 10 deletions(-) create mode 100644 chapter7/README.md create mode 100644 chapter7/dfs_dirtrav.py diff --git a/chapter7/README.md b/chapter7/README.md new file mode 100644 index 0000000..84d0f79 --- /dev/null +++ b/chapter7/README.md @@ -0,0 +1,5 @@ +# DFS BFS on rooted tree + +The BFS example uses a queue which results in a breadth first search. When a directory is found its contents are appended to the queue to be processed later + +The DFS example uses the call stack which results in a depth first search. When a directory is found it is recursively passed to files_with_extension to be processed immediately. diff --git a/chapter7/bfs_dirtrav.py b/chapter7/bfs_dirtrav.py index b200c9a..6d6bfeb 100644 --- a/chapter7/bfs_dirtrav.py +++ b/chapter7/bfs_dirtrav.py @@ -5,23 +5,27 @@ from pathlib import Path logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) +EXT = ".rb" + scripts_path = Path.home() / "scripts" -def files_with_extension(ext): +def files_with_extension(start_directory): queue = deque() - queue += scripts_path.glob("*") + queue.append(start_directory) while queue: - item = queue.popleft() + items = queue.popleft() - # if it is a file and has extension ext then print - if item.is_file() and item.suffix == ext: - print(item) + for item in items.glob("*"): + # if it is a file and has extension EXT then print + if item.is_file(): + if item.suffix == EXT: + print(item) - # otherwise add directory items to the queue - else: - queue += item.glob("*") + # otherwise append directory to the queue + else: + queue.append(item) -files_with_extension(".sh") +files_with_extension(scripts_path) diff --git a/chapter7/dfs_dirtrav.py b/chapter7/dfs_dirtrav.py new file mode 100644 index 0000000..f598891 --- /dev/null +++ b/chapter7/dfs_dirtrav.py @@ -0,0 +1,25 @@ +import logging +from collections import deque +from pathlib import Path + +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +EXT = ".rb" + +scripts_path = Path.home() / "scripts" + + +def files_with_extension(directory): + for item in directory.glob("*"): + # if it is a file and has extension EXT then print + if item.is_file(): + if item.suffix == EXT: + print(item) + + # otherwise pass directory to recursive call + else: + files_with_extension(item) + + +files_with_extension(scripts_path)