图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

78 lines
2.0 KiB

  1. from .edge import Edge
  2. from .node import Node
  3. class Path:
  4. def __init__(self, nodes, edges):
  5. if not (isinstance(nodes, list) and isinstance(edges, list)):
  6. raise TypeError("nodes and edges must be list")
  7. self._nodes = nodes
  8. self._edges = edges
  9. self.append_type = Node
  10. @classmethod
  11. def new_empty_path(cls):
  12. return cls([], [])
  13. def nodes(self):
  14. return self._nodes
  15. def edges(self):
  16. return self._edges
  17. def get_node(self, index):
  18. return self._nodes[index]
  19. def get_relationship(self, index):
  20. return self._edges[index]
  21. def first_node(self):
  22. return self._nodes[0]
  23. def last_node(self):
  24. return self._nodes[-1]
  25. def edge_count(self):
  26. return len(self._edges)
  27. def nodes_count(self):
  28. return len(self._nodes)
  29. def add_node(self, node):
  30. if not isinstance(node, self.append_type):
  31. raise AssertionError("Add Edge before adding Node")
  32. self._nodes.append(node)
  33. self.append_type = Edge
  34. return self
  35. def add_edge(self, edge):
  36. if not isinstance(edge, self.append_type):
  37. raise AssertionError("Add Node before adding Edge")
  38. self._edges.append(edge)
  39. self.append_type = Node
  40. return self
  41. def __eq__(self, other):
  42. # Type checking
  43. if not isinstance(other, Path):
  44. return False
  45. return self.nodes() == other.nodes() and self.edges() == other.edges()
  46. def __str__(self):
  47. res = "<"
  48. edge_count = self.edge_count()
  49. for i in range(0, edge_count):
  50. node_id = self.get_node(i).id
  51. res += "(" + str(node_id) + ")"
  52. edge = self.get_relationship(i)
  53. res += (
  54. "-[" + str(int(edge.id)) + "]->"
  55. if edge.src_node == node_id
  56. else "<-[" + str(int(edge.id)) + "]-"
  57. )
  58. node_id = self.get_node(edge_count).id
  59. res += "(" + str(node_id) + ")"
  60. res += ">"
  61. return res