gentree.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. # -*- coding: utf-8 -*-
  2. # logic tree
  3. class GenTree(object):
  4. """Class for Generalization hierarchies (Taxonomy Tree).
  5. Store tree node in instances.
  6. self.value: node value
  7. self.level: tree level (top is 0)
  8. self.leaf_num: number of leaf node covered
  9. self.parent: ancestor node list
  10. self.child: direct successor node list
  11. self.cover: all nodes covered by current node
  12. """
  13. def __init__(self, value=None, parent=None, isleaf=False):
  14. self.value = ''
  15. self.level = 0
  16. self.leaf_num = 0
  17. self.parent = []
  18. self.child = []
  19. self.cover = {}
  20. if value is not None:
  21. self.value = value
  22. self.cover[value] = self
  23. if parent is not None:
  24. self.parent = parent.parent[:]
  25. self.parent.insert(0, parent)
  26. parent.child.append(self)
  27. self.level = parent.level + 1
  28. for t in self.parent:
  29. t.cover[self.value] = self
  30. if isleaf:
  31. t.leaf_num += 1
  32. def node(self, value):
  33. """Search tree with value, return GenTree node.
  34. return point to that node, or None if not exists
  35. """
  36. try:
  37. return self.cover[value]
  38. except KeyError:
  39. return None
  40. def __len__(self):
  41. """
  42. return number of leaf node covered by current node
  43. """
  44. return self.leaf_num