Created
March 18, 2021 01:34
-
-
Save pamelafox/8573ba5a0c22ebc93320d8d0ff77ba6c to your computer and use it in GitHub Desktop.
Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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