Skip to content

Instantly share code, notes, and snippets.

@jonathanslenders
Created December 21, 2018 12:43
Show Gist options
  • Select an option

  • Save jonathanslenders/cb7891db6a2067b4c95ba457c8cfe0d3 to your computer and use it in GitHub Desktop.

Select an option

Save jonathanslenders/cb7891db6a2067b4c95ba457c8cfe0d3 to your computer and use it in GitHub Desktop.
nodes2.py
class Leaf:
def __init__(self, val):
self.val = val
def values(self):
# Following two lines for debugging.
# So that we can see how many stack frames there
# are at the deepest level while traversing the tree.
import traceback; traceback.print_stack()
import sys; sys.exit(0)
yield self.val
class Node:
def __init__(self, children):
self.children = children
def values(self):
for c in self.children:
yield from c.values()
def value(self):
return sum(self.values())
data = Node([
Node([
Node([
Node([
Leaf(1),
Leaf(2),
Leaf(3),
]),
Node([
Leaf(4),
Leaf(5),
Leaf(6),
]),
]),
Node([
Node([
Leaf(7),
Leaf(8),
Leaf(9),
]),
Node([
Leaf(10),
Leaf(11),
Leaf(12),
]),
])
])
])
data.value()
# Output:
"""
File "/tmp/nodes.py", line 58, in <module>
data.value()
File "/tmp/nodes.py", line 25, in value
return sum(self.values())
File "/tmp/nodes.py", line 22, in values
yield from c.values()
File "/tmp/nodes.py", line 22, in values
yield from c.values()
File "/tmp/nodes.py", line 22, in values
yield from c.values()
File "/tmp/nodes.py", line 10, in values
import traceback; traceback.print_stack()
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment