Skip to content

Instantly share code, notes, and snippets.

@mzmmoazam
Created July 17, 2018 07:46
Show Gist options
  • Save mzmmoazam/19c89a1f9c9ddd195e62d909e8e1542e to your computer and use it in GitHub Desktop.
Save mzmmoazam/19c89a1f9c9ddd195e62d909e8e1542e to your computer and use it in GitHub Desktop.
Apply DFS and BFS on file system,
from os import listdir,sep
from os.path import isfile,isdir,split,join
class Traversal(object):
def __init__(self,starting_node,dfs=True,bfs=False):
'''
:param starting_node: give absolute path of the directory to be travesed
:param dfs: set True for Debth first traversal ; default : True
:param bfs: set true for breadth first traversal ; default : False
'''
self._base_dir = starting_node
if dfs:
self._dfs(starting_node)
if bfs:
self._bfs(starting_node)
def _dfs(self,node):
if isfile(node):
level = node.replace(self._base_dir, '').count(sep)
indent = ' ' * 4 * (level)
print(indent,"- ->",node)
else:
level = node.replace(self._base_dir, '').count(sep)
indent = ' ' * 4 * (level)
print(indent,node)
for inner_node in listdir(node):
self._dfs(join(node,inner_node))
def _bfs(self,node):
if isdir(node):
level = node.replace(self._base_dir, '').count(sep)
indent = ' ' * 4 * (level)
print(indent, node)
for inner_node in listdir(node):
# self._bfs(join(node, inner_node))
print(indent, "- ->", join(node, inner_node))
for inner_node in listdir(node):
self._bfs(join(node, inner_node))
Traversal("C:\\Users\mzm\Desktop\intern_test")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment