Last active
October 7, 2019 11:03
-
-
Save CMCDragonkai/a8af37a803c8ce0a57dc to your computer and use it in GitHub Desktop.
Python: Rose Tree - every node has a name, and dictionary of children
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_abs_paths_for_immediate_children (tree, input_paths_string): | |
input_paths = input_paths_string.strip().split(".") | |
tmp_tree = tree | |
for input_path in input_paths: | |
tmp_tree = tmp_tree.n(input_path) | |
output_paths = [] | |
children = list(tmp_tree.children.keys()) | |
# to get the absolute paths for the entire tree, we would need to recurse into the children until the end | |
# and append that to the children list, then add for each! | |
for child in children: | |
output_paths.append(input_paths_string + "." + child) | |
return output_paths |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RoseTree: | |
def __init__ (self, name): | |
self.node = name | |
self.children = {} | |
def n (self, member): | |
return self.children[member] | |
def __str__ (self): | |
return self.node + " " + str(self.children) | |
def dump_it (self, tree=None, level=0): | |
# by default, `tree` should be self, otherwise, `tree` should be passed in | |
if tree is None: | |
tree = self | |
pretty_print = (" " * level) + tree.node + "\n" | |
for child in tree.children: | |
pretty_print += self.dump_it (tree.children[child], level + 1) | |
return pretty_print |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment