mirror of
https://github.com/onyx-and-iris/grokking-algorithms.git
synced 2024-11-15 17:30:52 +00:00
upd bfs, dfs on rooted tree
add readme
This commit is contained in:
parent
77b0993d73
commit
33a56b2e20
5
chapter7/README.md
Normal file
5
chapter7/README.md
Normal file
@ -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.
|
@ -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)
|
||||
|
25
chapter7/dfs_dirtrav.py
Normal file
25
chapter7/dfs_dirtrav.py
Normal file
@ -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)
|
Loading…
Reference in New Issue
Block a user