Advertisement
Guest User

Untitled

a guest
Mar 20th, 2019
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. class Node:
  2. emty_path = ' '
  3. parent_path = '│ '
  4. node_middle = '├─{}─'
  5. node_last = '└─{}─'
  6.  
  7. def __init__(self, attribute):
  8. self.attribute = attribute
  9. self.children = {}
  10.  
  11. def add_branch(self, attribute, subtree):
  12. self.children[attribute] = subtree
  13.  
  14. def __eq__(self, other):
  15. return self.attribute == other
  16.  
  17. def __repr__(self):
  18. if self.children:
  19. return f'A:{self.attribute+1}' # 1-index for easy reading
  20. return f'Class: {self.attribute}'
  21.  
  22. def __str__(self, level=0, parent_levels=[], identifier='', last=False):
  23. """ Hard to read, but print looks real nice."""
  24. ret = [self.emty_path]*(level)
  25.  
  26. for i in parent_levels:
  27. ret[i] = self.parent_path
  28.  
  29. prefix = ''
  30. if level > 0:
  31. if last:
  32. prefix = self.node_last.format(str(identifier))
  33. else:
  34. prefix = self.node_middle.format(str(identifier))
  35.  
  36. ret = ''.join(ret[:-1]) + prefix + repr(self) + '\n'
  37.  
  38. if self.children:
  39. parent_levels.append(level)
  40. for i, (key, child) in enumerate(self.children.items(), start=1):
  41. if i == len(self.children): # Last child for node
  42. parent_levels.remove(level)
  43. ret += child.__str__(level+1, parent_levels,
  44. identifier=key, last=True)
  45. else:
  46. ret += child.__str__(level+1, parent_levels,
  47. identifier=key)
  48. return ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement