Lecture 17 Trees (class)
- Questions
- Trees
- Tree class definition
- self.branches is always a list of Tree objects
- Trees are recursive by nature
- Tree terminology
- If t is an instance of a tree
- Variable t is pointing at the root of our tree
- Individual tree objects contained within it known as nodes
- ADT Trees vs OOP Tree
- Know the differences
- OOP Tree is Capital letters for a class
- ADT Tree is lowercase for a method
- Accessing branches attribute
- Branches are a list of trees
- t.branches[0] ← to get the first branch
- t.branches[1].branches[2] ← Nested branches
- What is t.branches?
- It is a list of tree objects, not Tree objects themselves
- Tree processing
- Each Tree has
- A label
- 0 or more branches, which are themselves Trees
- Most of our algorithms to process trees are going to be recursive
- Each Tree has
- Tree class definition
- Examples
Count Trees
def count_leaves(t):
if t.is_leaf():
return 1
else:
sum = 0
for b in t.branches:
sum += count_leaves(b)
return sum
#also able to do one line solution
#return sum([counter_leaves(b) for b in t.branches])
List leaves
#Returns a list of leaf labels of T
def list_leaves(t):
if t.is_leaf():
return [t.label]
else:
counter = []
for b in t.branches:
counter += list_leaves(b)
return counter
#two liner
#list_of_lists = [list_leaves(b) for b in t.branches]
#return sum(list_of_lists, start=[])
Count Paths
def count_paths(t, total):
counter = 0
if total == t.label:
counter += 1
for b in t.branches:
counter += count_paths(b, total-t.label)
return counter
#Two liner
# found = int(t.label == total)
# return sum([count_paths(b, total-t.label) for b in t.branches]) + found
- String Representation
#prints the nodes of the tree with depth based indent
def print_tree(t):
def helper(t, indent):
print (indent * " " + str(t.label))
for b in t.branches:
helper(b, indent + 2) #2 is an arbitrary number, just the amt of indent we want
helper(t, 0)
#If you need to carry information across recursive calls, use a helper function
- there technically is no base case
- For loop doesn’t execute if branches is empty
- that is our unofficial base case
- For loop doesn’t execute if branches is empty
- Mutating Trees
Mutates T such that every label is doubled
#return value of this function is none
#should actually be mutating the tree
def double_mut(t):
t.label *= 2
for b in t.branches:
double_mut(b)
- Syntax Trees
- Syntax is the branch of linguistics that studies sentence structure
- Syntax Trees aim to model the structure of languages in a way that’s easy to visualized