Skip to content

Instantly share code, notes, and snippets.

@pamelafox
Created March 18, 2021 01:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pamelafox/8573ba5a0c22ebc93320d8d0ff77ba6c to your computer and use it in GitHub Desktop.
Save pamelafox/8573ba5a0c22ebc93320d8d0ff77ba6c to your computer and use it in GitHub Desktop.
Tree
class Tree:
"""A tree."""
def __init__(self, label, branches=[]):
self.label = label
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)
def __repr__(self):
if self.branches:
branch_str = ', ' + repr(self.branches)
else:
branch_str = ''
return 'Tree({0}{1})'.format(self.label, branch_str)
def __str__(self):
return '\n'.join(self.indented())
def indented(self):
lines = []
for b in self.branches:
for line in b.indented():
lines.append(' ' + line)
return [str(self.label)] + lines
def is_leaf(self):
return not self.branches
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment