网址 https://inst.eecs.berkeley.edu/~cs61a/fa21/hw/hw06/
problem1:
没什么难度就是看清楚逻辑照着写就好了
class VendingMachine: """A vending machine that vends some product for some price. >>> v = VendingMachine('candy', 10) >>> v.vend() 'Nothing left to vend. Please restock.' >>> v.add_funds(15) 'Nothing left to vend. Please restock. Here is your $15.' >>> v.restock(2) 'Current candy stock: 2' >>> v.vend() 'You must add $10 more funds.' >>> v.add_funds(7) 'Current balance: $7' >>> v.vend() 'You must add $3 more funds.' >>> v.add_funds(5) 'Current balance: $12' >>> v.vend() 'Here is your candy and $2 change.' >>> v.add_funds(10) 'Current balance: $10' >>> v.vend() 'Here is your candy.' >>> v.add_funds(15) 'Nothing left to vend. Please restock. Here is your $15.' >>> w = VendingMachine('soda', 2) >>> w.restock(3) 'Current soda stock: 3' >>> w.restock(3) 'Current soda stock: 6' >>> w.add_funds(2) 'Current balance: $2' >>> w.vend() 'Here is your soda.' """ "*** YOUR CODE HERE ***" def __init__(self, name, price): self.name = name self.price = price self.stock = 0 self.CurBal = 0 def vend(self): if self.stock > 0: if self.price > self.CurBal: print(f"'You must add ${self.price - self.CurBal} more funds.'") elif self.price < self.CurBal: print(f"'Here is your {self.name} and ${self.CurBal - self.price } change.'") self.CurBal = 0 self.stock -= 1 else : print(f"'Here is your {self.name}.'") self.CurBal = 0 self.stock -= 1 else : print(f"'Nothing left to vend. Please restock.'") def restock(self, num): self.stock += num print(f"'Current {self.name} stock: {self.stock}'") def add_funds(self, num): if self.stock <= 0: print(f"'Nothing left to vend. Please restock. Here is your ${num}.'") return self.CurBal += num print(f"'Current balance: ${self.CurBal}'")
problem2:
在子类中的属性可以在父类提前使用(?)
class Mint: """A mint creates coins by stamping on years. The update method sets the mint's stamp to Mint.present_year. >>> mint = Mint() >>> mint.year 2021 >>> dime = mint.create(Dime) >>> dime.year 2021 >>> Mint.present_year = 2101 # Time passes >>> nickel = mint.create(Nickel) >>> nickel.year # The mint has not updated its stamp yet 2021 >>> nickel.worth() # 5 cents + (80 - 50 years) 35 >>> mint.update() # The mint's year is updated to 2101 >>> Mint.present_year = 2176 # More time passes >>> mint.create(Dime).worth() # 10 cents + (75 - 50 years) 35 >>> Mint().create(Dime).worth() # A new mint has the current year 10 >>> dime.worth() # 10 cents + (155 - 50 years) 115 >>> Dime.cents = 20 # Upgrade all dimes! >>> dime.worth() # 20 cents + (155 - 50 years) 125 """ present_year = 2021 def __init__(self): self.update() def create(self, kind): "*** YOUR CODE HERE ***" return kind(self.year) def update(self): "*** YOUR CODE HERE ***" self.year = Mint.present_year class Coin: def __init__(self, year): self.year = year def worth(self): "*** YOUR CODE HERE ***" return self.cents + max(0,Mint.present_year - self.year - 50) class Nickel(Coin): cents = 5 class Dime(Coin): cents = 10
problem3:
def store_digits(n): """Stores the digits of a positive number n in a linked list. >>> s = store_digits(1) >>> s Link(1) >>> store_digits(2345) Link(2, Link(3, Link(4, Link(5)))) >>> store_digits(876) Link(8, Link(7, Link(6))) >>> # a check for restricted functions >>> import inspect, re >>> cleaned = re.sub(r"#.*\\n", '', re.sub(r'"{3}[\s\S]*?"{3}', '', inspect.getsource(store_digits))) >>> print("Do not use str or reversed!") if any([r in cleaned for r in ["str", "reversed"]]) else None >>> link1 = Link(3, Link(Link(4), Link(5, Link(6)))) """ "*** YOUR CODE HERE ***" result = Link.empty while n > 0: result = Link(n%10, result) n = n // 10 return result
problem4:
不好理解的的话可以暂时先理解为列表
def deep_map_mut(fn, link): """Mutates a deep link by replacing each item found with the result of calling fn on the item. Does NOT create new Links (so no use of Link's constructor) Does not return the modified Link object. >>> link1 = Link(3, Link(Link(4), Link(5, Link(6)))) >>> # Disallow the use of making new Links before calling deep_map_mut >>> Link.__init__, hold = lambda *args: print("Do not create any new Links."), Link.__init__ >>> try: ... deep_map_mut(lambda x: x * x, link1) ... finally: ... Link.__init__ = hold >>> print(link1) <9 <16> 25 36> """ "*** YOUR CODE HERE ***" if link is Link.empty: return elif isinstance(link.first, Link): deep_map_mut(fn, link.first) else: link.first = fn(link.first) deep_map_mut(fn, link.rest)
problem5:
def two_list(vals, amounts): """ Returns a linked list according to the two lists that were passed in. Assume vals and amounts are the same size. Elements in vals represent the value, and the corresponding element in amounts represents the number of this value desired in the final linked list. Assume all elements in amounts are greater than 0. Assume both lists have at least one element. >>> a = [1, 3, 2] >>> b = [1, 1, 1] >>> c = two_list(a, b) >>> c Link(1, Link(3, Link(2))) >>> a = [1, 3, 2] >>> b = [2, 2, 1] >>> c = two_list(a, b) >>> c Link(1, Link(1, Link(3, Link(3, Link(2))))) """ "*** YOUR CODE HERE ***" vals.reverse() amounts.reverse() result = Link.empty for i in range(len(vals)): for j in range(amounts[i]): result = Link(vals[i], result) return result
peoblem6:
可以理解为每个class有两个属性,一个是本身的值,一个前一个值这样就根据自己就可以计算出下一个数字
class VirFib(): """A Virahanka Fibonacci number. >>> start = VirFib() >>> start VirFib object, value 0 >>> start.next() VirFib object, value 1 >>> start.next().next() VirFib object, value 1 >>> start.next().next().next() VirFib object, value 2 >>> start.next().next().next().next() VirFib object, value 3 >>> start.next().next().next().next().next() VirFib object, value 5 >>> start.next().next().next().next().next().next() VirFib object, value 8 >>> start.next().next().next().next().next().next() # Ensure start isn't changed VirFib object, value 8 """ def __init__(self, value=0): self.value = value self.previous = 0 def next(self): if self.value == 0: result = VirFib(1) else: result = VirFib(self.value + self.previous) result.previous = self.value return result def __repr__(self): return "VirFib object, value " + str(self.value)
problem7:
要注意每次都要带着一个最大值或者最小值,控制上限或者下限。
def is_bst(t): """Returns True if the Tree t has the structure of a valid BST. >>> t1 = Tree(6, [Tree(2, [Tree(1), Tree(4)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t1) True >>> t2 = Tree(8, [Tree(2, [Tree(9), Tree(1)]), Tree(3, [Tree(6)]), Tree(5)]) >>> is_bst(t2) False >>> t3 = Tree(6, [Tree(2, [Tree(4), Tree(1)]), Tree(7, [Tree(7), Tree(8)])]) >>> is_bst(t3) False >>> t4 = Tree(1, [Tree(2, [Tree(3, [Tree(4)])])]) >>> is_bst(t4) True >>> t5 = Tree(1, [Tree(0, [Tree(-1, [Tree(-2)])])]) >>> is_bst(t5) True >>> t6 = Tree(1, [Tree(4, [Tree(2, [Tree(3)])])]) >>> is_bst(t6) True >>> t7 = Tree(2, [Tree(1, [Tree(5)]), Tree(4)]) >>> is_bst(t7) False """ "*** YOUR CODE HERE ***" def func(tree, max, min): if tree.is_leaf() : if tree.label <= max and tree.label > min: return True else : return False elif len(tree.branches) == 1: if tree.label <= max and tree.label > min and tree.branches[0].label <= max and tree.branches[0].label > min: return True else : return False elif tree.label <= max and tree.label > min : return func(tree.branches[0], tree.label, -float('inf')) and func(tree.branches[1], float('inf'), tree.label) else : return False return func(t, float('inf'), -float('inf'))