""" Lab 08: Midterm Review """ # Link class class Link: """A linked list. >>> s = Link(1) >>> s.first 1 >>> s.rest is Link.empty True >>> s = Link(2, Link(3, Link(4))) >>> s.second 3 >>> s.first = 5 >>> s.second = 6 >>> s.rest.rest = Link.empty >>> s # Displays the contents of repr(s) Link(5, Link(6)) >>> s.rest = Link(7, Link(Link(8, Link(9)))) >>> s Link(5, Link(7, Link(Link(8, Link(9))))) >>> print(s) # Prints str(s) <5 7 <8 9>> """ empty = () def __init__(self, first, rest=empty): assert rest is Link.empty or isinstance(rest, Link) self.first = first self.rest = rest @property def second(self): return self.rest.first @second.setter def second(self, value): self.rest.first = value def __repr__(self): if self.rest is not Link.empty: rest_repr = ', ' + repr(self.rest) else: rest_repr = '' return 'Link(' + repr(self.first) + rest_repr + ')' def __str__(self): string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>' # Linked lists def deep_len(lnk): """ Returns the deep length of a possibly deep linked list. >>> deep_len(Link(1, Link(2, Link(3)))) 3 >>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4)))) 4 >>> levels = Link(Link(Link(1, Link(2)), \ Link(3)), Link(Link(4), Link(5))) >>> print(levels) <<<1 2> 3> <4> 5> >>> deep_len(levels) 5 """ "*** YOUR CODE HERE ***" # Recursion/Tree Recursion def insert_into_all(item, nested_list): """Assuming that nested_list is a list of lists, return a new list consisting of all the lists in nested_list, but with item added to the front of each. >>> nl = [[], [1, 2], [3]] >>> insert_into_all(0, nl) [[0], [0, 1, 2], [0, 3]] """ "*** YOUR CODE HERE ***" def subseqs(s): """Assuming that S is a list, return a nested list of all subsequences of S (a list of lists). The subsequences can appear in any order. >>> seqs = subseqs([1, 2, 3]) >>> sorted(seqs) [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]] >>> subseqs([]) [[]] """ "*** YOUR CODE HERE ***" def inc_subseqs(s): """Assuming that S is a list, return a nested list of all subsequences of S (a list of lists) for which the elements of the subsequence are strictly nondecreasing. The subsequences can appear in any order. >>> seqs = inc_subseqs([1, 3, 2]) >>> sorted(seqs) [[], [1], [1, 2], [1, 3], [2], [3]] >>> inc_subseqs([]) [[]] >>> seqs2 = inc_subseqs([1, 1, 2]) >>> sorted(seqs2) [[], [1], [1], [1, 1], [1, 1, 2], [1, 2], [1, 2], [2]] """ def subseq_helper(s, prev): if not s: return ____________________ elif s[0] < prev: return ____________________ else: a = ______________________ b = ______________________ return insert_into_all(________, ______________) + ________________ return subseq_helper(____, ____)