from lab04 import * # Q7 def make_pytunes(username): """Return a pyTunes tree as shown in the diagram with USERNAME as the value of the root. >>> pytunes = make_pytunes('i_love_music') >>> print_tree(pytunes) i_love_music pop justin bieber single what do you mean? 2015 pop mashup trance darude sandstorm """ "*** YOUR CODE HERE ***" # Q8 def num_songs(t): """Return the number of songs in the pyTunes tree, t. >>> pytunes = make_pytunes('i_love_music') >>> num_songs(pytunes) 3 """ "*** YOUR CODE HERE ***" # Q9 def add_song(t, song, category): """Returns a new tree with SONG added to CATEGORY. Assume the CATEGORY already exists. >>> indie_tunes = tree('indie_tunes', ... [tree('indie', ... [tree('vance joy', ... [tree('riptide')])])]) >>> new_indie = add_song(indie_tunes, 'georgia', 'vance joy') >>> print_tree(new_indie) indie_tunes indie vance joy riptide georgia """ "*** YOUR CODE HERE ***" # Q10 def delete(t, target): """Returns the tree that results from deleting TARGET from t. If TARGET is a category, delete everything inside of it. >>> my_account = tree('kpop_king', ... [tree('korean', ... [tree('gangnam style'), ... tree('wedding dress')]), ... tree('pop', ... [tree('t-swift', ... [tree('blank space')]), ... tree('uptown funk'), ... tree('see you again')])]) >>> new = delete(my_account, 'pop') >>> print_tree(new) kpop_king korean gangnam style wedding dress """ "*** YOUR CODE HERE ***" # Tree ADT Definition def tree(label, branches=[]): for branch in branches: assert is_tree(branch), 'branches must be trees' return [label] + list(branches) def label(tree): return tree[0] def branches(tree): return tree[1:] def is_tree(tree): if type(tree) != list or len(tree) < 1: return False for branch in branches(tree): if not is_tree(branch): return False return True def is_leaf(tree): return not branches(tree) def print_tree(t, indent=0): """Print a representation of this tree in which each node is indented by two spaces times its depth from the label. >>> print_tree(tree(1)) 1 >>> print_tree(tree(1, [tree(2)])) 1 2 >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])]) >>> print_tree(numbers) 1 2 3 4 5 6 7 """ print(' ' * indent + str(label(t))) for b in branches(t): print_tree(b, indent + 1)