Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Created January 16, 2019 17:59
Show Gist options
  • Save rupalbarman/1c8fc4ae32e4dad86c408ee88d5be67d to your computer and use it in GitHub Desktop.
Save rupalbarman/1c8fc4ae32e4dad86c408ee88d5be67d to your computer and use it in GitHub Desktop.
Print filesystem directory structure using trie datastructure
'''
Coding Problem Statement
Given a list of file paths (e.g. as output by grep), pretty print all the paths in a tree-like format.
Write your code as the prettyPrint function (do not assume the input is sorted):
String[] prettyPrint(String[] files);
Example Input:
/a/b/c/d
/b/b/f
/foo/bar
/a/c/m
/a/b/f
Example Output:
Red Sox : Yankees 24th Feb 2000
/a
/b
/c
/d (Re: Socks, Yankess 25 Feb 2000) (RedSocks: 24th )
/x ()
/f
/c/m
/b/b/f
/foo/bar
Note:
If a directory has multiple sub-directories, each sub-directory sub-tree should appear on a new line
If a directory has only one sub-directory, it should appear on the same line as the parent directory
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
class Trie(object):
def __init__(self):
self.nodes = dict()
self.end = False
def add(home, path):
if len(path) <= 0:
return
aux = home
path = path.split('/')[1:]
for i, d in enumerate(path):
if aux.nodes.get(d, None) is not None:
aux = aux.nodes.get(d)
else:
aux.nodes[d] = Trie()
aux = aux.nodes[d]
aux.end = True
return home
def show(home, padding = 0):
assert home is not None
for k, v in home.nodes.items():
remaining = len(v.nodes)
if remaining == 0:
# end flag
print((' ' * padding) + '/' + k)
show(v, 0)
else:
print((' ' * padding) + '/' + k, end = ' ' if remaining == 1 else '\n')
show(v, padding+1)
def main():
home = Trie()
home = add(home, '/a/b/c/d')
home = add(home, '/a/c/m')
home = add(home, '/foo/bar')
home = add(home, '/a/b/f')
show(home)
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment