Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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
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 # Returns 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: rest_str = ', ' + repr(self.rest) else: rest_str = '' return 'Link({0}{1})'.format(repr(self.first), rest_str) def __str__(self): """Returns a human-readable string representation of the Link >>> s = Link(1, Link(2, Link(3, Link(4)))) >>> str(s) '<1 2 3 4>' >>> str(Link(1)) '<1>' >>> str(Link.empty) # empty tuple '()' """ string = '<' while self.rest is not Link.empty: string += str(self.first) + ' ' self = self.rest return string + str(self.first) + '>'
def test_empty(link): if link is Link.empty: print('This linked list is empty!') else: print('This linked list is not empty!')
class Tree: def __init__(self, label, branches=[]): for c in branches: assert isinstance(c, Tree) self.label = label self.branches = list(branches) def __repr__(self): if self.branches: branches_str = ', ' + repr(self.branches) else: branches_str = '' return 'Tree({0}{1})'.format(self.label, branches_str) def is_leaf(self): return not self.branches def __eq__(self, other): return type(other) is type(self) and self.label == other.label \ and self.branches == other.branches def __str__(self): def print_tree(t, indent=0): tree_str = ' ' * indent + str(t.label) + " " for b in t.branches: tree_str += print_tree(b, indent + 1) return tree_str return print_tree(self).rstrip() def copy_tree(self): return Tree(self.label, [b.copy_tree() for b in self.branches])
>>> from lab07 import * >>> link = Link(5, Link(6, Link(7))) >>> link.second
______
>>> link.rest.second
______
>>> link.second = 10 >>> link # Look at the __repr__ method of Link
______
>>> link.second = Link(8, Link(9)) >>> link.second.first
______
>>> print(link) # Look at the __str__ method of Link
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started