Skip to content

pydsa.nodes

TreeNode

Source code in pydsa/nodes.mu
3
4
5
class TreeNode
  def __init__(val=0, left=none, right=none)
    self.val, self.left, self.right = val, left, right
24
25
26
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

ListNode

Source code in pydsa/nodes.mu
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class ListNode
  def __init__(val=0, next=none): self.val, self.next = val, next

  # Ordering by val, so heaps/sorts of nodes work like a ListNode.__lt__
  # override does on leetcode. No __eq__/__hash__: those must stay identity,
  # or seen-sets and cycle detection break on duplicate vals.
  def __lt__(other): self.val < other.val
  def __le__(other): self.val <= other.val
  def __gt__(other): self.val > other.val
  def __ge__(other): self.val >= other.val

  def __repr__()
    vals, seen, it = [], set(), self
    while it and it not in seen
      seen.add(it)
      vals <- str(it.val)
      it = it.next
    "->".join(vals)
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class ListNode:
    def __init__(self, val=0, next=None):
        self.val, self.next = val, next

    def __lt__(self, other):
        return self.val < other.val

    def __le__(self, other):
        return self.val <= other.val

    def __gt__(self, other):
        return self.val > other.val

    def __ge__(self, other):
        return self.val >= other.val

    def __repr__(self):
        vals, seen, it = [], set(), self
        while it and it not in seen:
            seen.add(it)
            vals.append(str(it.val))
            it = it.next
        return "->".join(vals)

GraphNode

Source code in pydsa/nodes.mu
26
27
28
29
30
class GraphNode
  def __init__(val=0, neighbors=none)
    self.val, self.neighbors = val, neighbors is none ? [] : neighbors

  def __repr__(): f"{self.val} -> ..."
54
55
56
57
58
59
class GraphNode:
    def __init__(self, val=0, neighbors=None):
        self.val, self.neighbors = val, [] if neighbors is None else neighbors

    def __repr__(self):
        return f"{self.val} -> ..."

Node

Source code in pydsa/nodes.mu
32
33
34
35
36
37
class Node
  # parent=p adds the new node to p.children, as anytree's Node(name, parent=p)
  def __init__(val, children: {Any: "Node"}?=none, parent: "Node"?=none)
    self.val, self.children = val, children is none ? {} : children
    if parent is not none
      parent.children[len(parent.children)] = self
62
63
64
65
66
class Node:
    def __init__(self, val, children: Optional[dict[Any, "Node"]] = None, parent: Optional["Node"] = None):
        self.val, self.children = val, Rec() if children is None else children
        if parent is not None:
            parent.children[len(parent.children)] = self