楼主: smoothiethu
跳转到指定楼层
上一主题 下一主题
收起左侧

2018 Spring CS61a打卡与作业答案

🔗
chenwang9527 2019-8-7 02:52:00 | 只看该作者
全局:
楼主你好, 请问你在哪里找的 full lecture video?  http://inst.eecs.berkeley.edu/~cs61a/sp18/ 这个网站上的video都只有2,3 分钟的。 谢谢
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-7 03:11:07 | 只看该作者
全局:
chenwang9527 发表于 2019-8-7 02:52
楼主你好, 请问你在哪里找的 full lecture video?  http://inst.eecs.berkeley.edu/~cs61a/sp18/ 这个网站 ...

那个youtube上面的视频都是五六个一起的,后面的是往年的视频。要一起看完的
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-7 14:19:55 | 只看该作者
全局:
今天利用下午和晚上break时间刷了一周课程,课程上到了第七周,作业还在第六周。这周末要把第六周的作业,discussion搞定。
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-9 15:50:28 | 只看该作者
全局:
今天看完了Weeks 8 的Composition,做了HW5的non extra部分。。。题目好难= =,好多都不会。。。我好差。。
回复

使用道具 举报

🔗
jshalyf 2019-8-10 04:36:04 | 只看该作者
全局:
其实在现在进行的2019summer的网页上能找到作业,discussion答案跟视频walk through的
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-10 08:52:40 | 只看该作者
全局:
jshalyf 发表于 2019-8-10 04:36
其实在现在进行的2019summer的网页上能找到作业,discussion答案跟视频walk through的

这样呀。。我没上最新版的。。谢谢!
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-11 12:56:09 | 只看该作者
全局:
  1. """Lab 1: Expressions and Control Structures"""

  2. # Coding Practice
  3. # cd ~/Desktop/cs61a/lab/lab01

  4. def repeated(f, n, x):
  5.     """Returns the result of composing f n times on x.

  6.     >>> def square(x):
  7.     ...     return x * x
  8.     ...
  9.     >>> repeated(square, 2, 3)  # square(square(3)), or 3 ** 4
  10.     81
  11.     >>> repeated(square, 1, 4)  # square(4)
  12.     16
  13.     >>> repeated(square, 6, 2)  # big number
  14.     18446744073709551616
  15.     >>> def opposite(b):
  16.     ...     return not b
  17.     ...
  18.     >>> repeated(opposite, 4, True)
  19.     True
  20.     >>> repeated(opposite, 5, True)
  21.     False
  22.     >>> repeated(opposite, 631, 1)
  23.     False
  24.     >>> repeated(opposite, 3, 0)
  25.     True
  26.     """
  27.     "*** YOUR CODE HERE ***"
  28.     i = 0
  29.     while i < n:
  30.         x = f(x)
  31.         i += 1
  32.     return x
  33.    
  34.    
  35. def sum_digits(n):
  36.     """Sum all the digits of n.

  37.     >>> sum_digits(10) # 1 + 0 = 1
  38.     1
  39.     >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
  40.     12
  41.     >>> sum_digits(1234567890)
  42.     45
  43.     """
  44.     "*** YOUR CODE HERE ***"
  45.     sum = 0
  46.     while n != 0:
  47.         n, digit = n//10, n%10
  48.         sum = sum + digit
  49.     return sum
  50.         
  51.    
  52.    
  53.    
  54. def double_eights(n):
  55.     """Return true if n has two eights in a row.
  56.     >>> double_eights(8)
  57.     False
  58.     >>> double_eights(88)
  59.     True
  60.     >>> double_eights(2882)
  61.     True
  62.     >>> double_eights(880088)
  63.     True
  64.     >>> double_eights(12345)
  65.     False
  66.     >>> double_eights(80808080)
  67.     False
  68.     """
  69.     "*** YOUR CODE HERE ***"
  70.     n_str = str(n)
  71.     if len(n_str) <= 1:
  72.         return False
  73.     for i in range(len(n_str)-1):
  74.         if n_str[i] == '8' and n_str[i+1] == '8':
  75.             return True
  76.     return False
  77.    
  78.         
  79.         
  80.         
  81.         
  82.         
  83.         
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-13 04:45:16 | 只看该作者
全局:
做完了hw05, extra的最后一题不太会 看的答案才懂得
  1. def tree(label, branches=[]):     """Construct a tree with the given label value and a list of branches."""     for branch in branches:         assert is_tree(branch), 'branches must be trees'     return [label] + list(branches)  def label(tree):     """Return the label value of a tree."""     return tree[0]  def branches(tree):     """Return the list of branches of the given tree."""     return tree[1:]  def is_tree(tree):     """Returns True if the given tree is a tree, and False otherwise."""     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):     """Returns True if the given tree's list of branches is empty, and False     otherwise.     """     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 root.      >>> 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)  def copy_tree(t):     """Returns a copy of t. Only for testing purposes.      >>> t = tree(5)     >>> copy = copy_tree(t)     >>> t = tree(6)     >>> print_tree(copy)     5     """     return tree(label(t), [copy_tree(b) for b in branches(t)])  ############# # Questions # #############  def replace_leaf(t, old, new):     """Returns a new tree where every leaf value equal to old has     been replaced with new.      >>> yggdrasil = tree('odin',     ...                  [tree('balder',     ...                        [tree('thor'),     ...                         tree('loki')]),     ...                   tree('frigg',     ...                        [tree('thor')]),     ...                   tree('thor',     ...                        [tree('sif'),     ...                         tree('thor')]),     ...                   tree('thor')])     >>> laerad = copy_tree(yggdrasil) # copy yggdrasil for testing purposes     >>> print_tree(replace_leaf(yggdrasil, 'thor', 'freya'))     odin       balder         freya         loki       frigg         freya       thor         sif         freya       freya     >>> laerad == yggdrasil # Make sure original tree is unmodified     True     """     "*** YOUR CODE HERE ***"     if is_leaf(t):         if label(t) == old:             return tree(new)         else:             return t     else:         new_branches = [replace_leaf(b, old, new) for b in branches(t)]         return tree(label(t), new_branches)  def print_move(origin, destination):     """Print instructions to move a disk."""     print("Move the top disk from rod", origin, "to rod", destination)  def move_stack(n, start, end):     """Print the moves required to move n disks on the start pole to the end     pole without violating the rules of Towers of Hanoi.      n -- number of disks     start -- a pole position, either 1, 2, or 3     end -- a pole position, either 1, 2, or 3      There are exactly three poles, and start and end must be different. Assume     that the start pole has at least n disks of increasing size, and the end     pole is either empty or has a top disk larger than the top n start disks.      >>> move_stack(1, 1, 3)     Move the top disk from rod 1 to rod 3     >>> move_stack(2, 1, 3)     Move the top disk from rod 1 to rod 2     Move the top disk from rod 1 to rod 3     Move the top disk from rod 2 to rod 3     >>> move_stack(3, 1, 3)     Move the top disk from rod 1 to rod 3     Move the top disk from rod 1 to rod 2     Move the top disk from rod 3 to rod 2     Move the top disk from rod 1 to rod 3     Move the top disk from rod 2 to rod 1     Move the top disk from rod 2 to rod 3     Move the top disk from rod 1 to rod 3     """     assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"     "*** YOUR CODE HERE ***"          if n == 1:         print_move(start, end)     else:         ## The sum of three rods is 6 (1, 2, 3)         mid = 6 - start - end         move_stack(n-1, start, mid)         print_move(start, end)         move_stack(n-1, mid, end)                           ########### # Mobiles # ###########  def mobile(left, right):     """Construct a mobile from a left side and a right side."""     return tree('mobile', [left, right])  def is_mobile(m):     return is_tree(m) and label(m) == 'mobile'  def sides(m):     """Select the sides of a mobile."""     assert is_mobile(m), "must call sides on a mobile"     return branches(m)  def is_side(m):     return not is_mobile(m) and not is_weight(m) and type(label(m)) == int  def side(length, mobile_or_weight):     """Construct a side: a length of rod with a mobile or weight at the end."""     return tree(length, [mobile_or_weight])  def length(s):     """Select the length of a side."""     assert is_side(s), "must call length on a side"     return label(s)  def end(s):     """Select the mobile or weight hanging at the end of a side."""     assert is_side(s), "must call end on a side"     return branches(s)[0]  def weight(size):     """Construct a weight of some size."""     assert size > 0     "*** YOUR CODE HERE ***"     return tree(size, [])      def size(w):     """Select the size of a weight."""     "*** YOUR CODE HERE ***"     return label(w)  def is_weight(w):     """Whether w is a weight, not a mobile."""     "*** YOUR CODE HERE ***"     if is_leaf(w):         return True     else:         return False  def examples():     t = mobile(side(1, weight(2)),                side(2, weight(1)))     u = mobile(side(5, weight(1)),                side(1, mobile(side(2, weight(3)),                               side(3, weight(2)))))     v = mobile(side(4, t), side(2, u))     return (t, u, v)   def total_weight(m):     """Return the total weight of m, a weight or mobile.      >>> t, u, v = examples()     >>> total_weight(t)     3     >>> total_weight(u)     6     >>> total_weight(v)     9     """     if is_weight(m):         return size(m)     else:         assert is_mobile(m), "must get total weight of a mobile or a weight"         return sum([total_weight(end(s)) for s in sides(m)])            def balanced(m):     """Return whether m is balanced.      >>> t, u, v = examples()     >>> balanced(t)     True     >>> balanced(v)     True     >>> w = mobile(side(3, t), side(2, u))     >>> balanced(w)     False     >>> balanced(mobile(side(1, v), side(1, w)))     False     >>> balanced(mobile(side(1, w), side(1, v)))     False     """     "*** YOUR CODE HERE ***"     ## 若第一次两边不balanced 直接false     if is_weight(m):         return True     elif length(sides(m)[0]) * total_weight(end(sides(m)[0])) != length(sides(m)[1]) * total_weight(end(sides(m)[1])):         return False     ## 若不为 weight,就扔进balanced函数中检测一遍。     else:         if_balanced = [balanced(end(x)) for x in sides(m)]         return all(if_balanced)          #    ### 其他人的答案d #    if is_weight(m): #        return True #    else: #        b = [balanced(end(s)) for s in sides(m)] #        weights = [total_weight(end(s)) for s in sides(m)] #        lengths = [length(s) for s in sides(m)] #         #        return all(b) and len(set(a * b for a, b in zip(lengths, weights))) == 1  ####### # OOP # #######  class Account:     """An account has a balance and a holder.      >>> a = Account('John')     >>> a.deposit(10)     10     >>> a.balance     10     >>> a.interest     0.02      >>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404     2     >>> a.balance               # balance should not change     10     >>> a.time_to_retire(11)    # 10 -> 10.2 -> ... -> 11.040808032     5     >>> a.time_to_retire(100)     117     """      interest = 0.02  # A class attribute      def __init__(self, account_holder):         self.holder = account_holder         self.balance = 0      def deposit(self, amount):         """Add amount to balance."""         self.balance = self.balance + amount         return self.balance      def withdraw(self, amount):         """Subtract amount from balance if funds are available."""         if amount > self.balance:             return 'Insufficient funds'         self.balance = self.balance - amount         return self.balance      def time_to_retire(self, amount):         """Return the number of years until balance would grow to amount."""         assert self.balance > 0 and amount > 0 and self.interest > 0         "*** YOUR CODE HERE ***"         year = 0         total = self.balance         while total < amount:             total = total + total * self.interest             year += 1         return year  class FreeChecking(Account):     """A bank account that charges for withdrawals, but the first two are free!      >>> ch = FreeChecking('Jack')     >>> ch.balance = 20     >>> ch.withdraw(100)  # First one's free     'Insufficient funds'     >>> ch.withdraw(3)    # And the second     17     >>> ch.balance     17     >>> ch.withdraw(3)    # Ok, two free withdrawals is enough     13     >>> ch.withdraw(3)     9     >>> ch2 = FreeChecking('John')     >>> ch2.balance = 10     >>> ch2.withdraw(3) # No fee     7     >>> ch.withdraw(3)  # ch still charges a fee     5     >>> ch.withdraw(5)  # Not enough to cover fee + withdraw     'Insufficient funds'     """     withdraw_fee = 1     free_withdrawals = 2      "*** YOUR CODE HERE ***"     def withdraw(self, amount):         if self.free_withdrawals > 0:             self.free_withdrawals -= 1             return Account.withdraw(self, amount)         else:             return Account.withdraw(self, amount + self.withdraw_fee)            ############ # Mutation # ############ ### 这道还是不会。。。 def make_counter():     """Return a counter function.      >>> c = make_counter()     >>> c('a')     1     >>> c('a')     2     >>> c('b')     1     >>> c('a')     3     >>> c2 = make_counter()     >>> c2('b')     1     >>> c2('b')     2     >>> c('b') + c2('b')     5     """     "*** YOUR CODE HERE ***"     str_dict = {}     def count(string):         nonlocal str_dict         if string in str_dict:             str_dict[string] += 1             return str_dict[string]         else:             str_dict[string] = 1             return str_dict[string]     return count                             def make_fib():     """Returns a function that returns the next Fibonacci number     every time it is called.      >>> fib = make_fib()     >>> fib()     0     >>> fib()     1     >>> fib()     1     >>> fib()     2     >>> fib()     3     >>> fib2 = make_fib()     >>> fib() + sum([fib2() for _ in range(5)])     12     """     "*** YOUR CODE HERE ***"     curr = 1     prev = 0     n = 1     def fib():         nonlocal curr, prev, n         if n == 1:             n += 1             return prev         elif n == 2:             n += 1             return curr         else:             n += 1             curr, prev = curr + prev, curr             return curr     return fib           def make_withdraw(balance, password):     """Return a password-protected withdraw function.      >>> w = make_withdraw(100, 'hax0r')     >>> w(25, 'hax0r')     75     >>> error = w(90, 'hax0r')     >>> error     'Insufficient funds'     >>> error = w(25, 'hwat')     >>> error     'Incorrect password'     >>> new_bal = w(25, 'hax0r')     >>> new     50     >>> w(75, 'a')     'Incorrect password'     >>> w(10, 'hax0r')     40     >>> w(20, 'n00b')     'Incorrect password'     >>> w(10, 'hax0r')     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"     >>> w(10, 'l33t')     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"     >>> type(w(10, 'l33t')) == str     True     """     "*** YOUR CODE HERE ***"     password_try = 3     password_lst = []     def withdraw(amount, input_password):         nonlocal password_try, password_lst, balance                  if password_try == 0:             return "Your account is locked. Attempts: " + str(password_lst)                   if input_password != password:             password_try -= 1             password_lst.append(input_password)             return 'Incorrect password'                  if amount > balance:             return 'Insufficient funds'         else:             balance = balance - amount             return balance              return withdraw                 def make_joint(withdraw, old_password, new_password):     """Return a password-protected withdraw function that has joint access to     the balance of withdraw.      >>> w = make_withdraw(100, 'hax0r')     >>> w(25, 'hax0r')     75     >>> make_joint(w, 'my', 'secret')     'Incorrect password'     >>> j = make_joint(w, 'hax0r', 'secret')     >>> w(25, 'secret')     'Incorrect password'     >>> j(25, 'secret')     50     >>> j(25, 'hax0r')     25     >>> j(100, 'secret')     'Insufficient funds'      >>> j2 = make_joint(j, 'secret', 'code')     >>> j2(5, 'code')     20     >>> j2(5, 'secret')     15     >>> j2(5, 'hax0r')     10      >>> j2(25, 'password')     'Incorrect password'     >>> j2(5, 'secret')     "Your account is locked. Attempts: ['my', 'secret', 'password']"     >>> j(5, 'secret')     "Your account is locked. Attempts: ['my', 'secret', 'password']"     >>> w(5, 'hax0r')     "Your account is locked. Attempts: ['my', 'secret', 'password']"     >>> make_joint(w, 'hax0r', 'hello')     "Your account is locked. Attempts: ['my', 'secret', 'password']"     """     "*** YOUR CODE HERE ***"     ### 自己这道题不会做= =,难受。     w = withdraw(0, old_password)     if type(w) == str:         return w          def joint_withdraw(amount, password):         if password == new_password or password == old_password:             return withdraw(amount, old_password)         else:             return withdraw(amount, password)              return joint_withdraw                                                                                                  ################### # Extra Questions # ###################  def interval(a, b):     """Construct an interval from a to b."""     return [a, b]  def lower_bound(x):     """Return the lower bound of interval x."""     "*** YOUR CODE HERE ***"     return x[0]  def upper_bound(x):     """Return the upper bound of interval x."""     "*** YOUR CODE HERE ***"     return x[1]  def str_interval(x):     """Return a string representation of interval x."""     return '{0} to {1}'.format(lower_bound(x), upper_bound(x))  def add_interval(x, y):     """Return an interval that contains the sum of any value in interval x and     any value in interval y."""     lower = lower_bound(x) + lower_bound(y)     upper = upper_bound(x) + upper_bound(y)     return interval(lower, upper)  def mul_interval(x, y):     """Return the interval that contains the product of any value in x and any     value in y."""     p1 = lower_bound(x) * lower_bound(y)     p2 = lower_bound(x) * upper_bound(y)     p3 = upper_bound(x) * lower_bound(y)     p4 = upper_bound(x) * upper_bound(y)     return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))  def sub_interval(x, y):     """Return the interval that contains the difference between any value in x     and any value in y."""     "*** YOUR CODE HERE ***"          return interval(lower_bound(x) - upper_bound(y), upper_bound(x) - lower_bound(y))  def div_interval(x, y):     """Return the interval that contains the quotient of any value in x divided by     any value in y. Division is implemented as the multiplication of x by the     reciprocal of y."""     "*** YOUR CODE HERE ***"     assert lower_bound(y) * upper_bound(y) > 0     reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))     return mul_interval(x, reciprocal_y)  def par1(r1, r2):     return div_interval(mul_interval(r1, r2), add_interval(r1, r2))  def par2(r1, r2):     one = interval(1, 1)     rep_r1 = div_interval(one, r1)     rep_r2 = div_interval(one, r2)     return div_interval(one, add_interval(rep_r1, rep_r2))  def check_par():     """Return two intervals that give different results for parallel resistors.      >>> r1, r2 = check_par()     >>> x = par1(r1, r2)     >>> y = par2(r1, r2)     >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)     True     """          r1 = interval(-2, -1) # Replace this line!     r2 = interval(3, 4) # Replace this line!     return r1, r2  def multiple_references_explanation():     return """The multiple reference problem...     par2 is a better method since it uses less functions like add, div sub, thus     creating less uncertainty compared with par1"""    def quadratic(x, a, b, c):     """Return the interval that is the range of the quadratic defined by     coefficients a, b, and c, for domain interval x.      >>> str_interval(quadratic(interval(0, 2), -2, 3, -1))     '-3 to 0.125'     >>> str_interval(quadratic(interval(1, 3), 2, -3, 1))     '0 to 10'     """     "*** YOUR CODE HERE ***"     extreme = -b/a/2     l = lower_bound(x)      u = upper_bound(x)     if l > extreme or u < extreme:         low = min(a*l*l + b*l + c, a*u*u + b*u + c)         high = max(a*l*l + b*l + c, a*u*u + b*u + c)     else:         low = min(a*l*l + b*l + c, a*u*u + b*u + c, a*extreme*extreme + b*extreme + c)         high = max(a*l*l + b*l + c, a*u*u + b*u + c, a*extreme*extreme + b*extreme + c)     return interval(low, high)            # Official solution  def polynomial(x, c):     """Return the interval that is the range of the polynomial defined by     coefficients c, for domain interval x.     >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))     '-3 to 0.125'     >>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))     '0 to 10'     >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))     '18.0 to 23.0'     """     # Newton's method from lecture      def improve(update, close, guess=1, max_updates=100):         """Iteratively improve guess with update until close(guess) is true or          max_updates have been applied."""         k = 0         while not close(guess) and k < max_updates:             guess = update(guess)             k = k + 1         return guess              def approx_eq(x, y, tolerance=1e-15):         return abs(x - y) < tolerance                  def find_zero(f, df, guess=1):         """Return a zero of the function f with derivative df."""         def near_zero(x):             return approx_eq(f(x), 0)         return improve(newton_update(f, df), near_zero, guess)              def newton_update(f, df):         """Return an update function for f with derivative df,         using Newton's method."""         def update(x):             return x - f(x) / df(x)         return update                    def add_fn(coeff, k, f):         return lambda x: coeff * pow(x, k) + f(x)      def add_dfn(coeff, k, df):         return lambda x: k * coeff * pow(x, k-1) + df(x)      def add_ddfn(coeff, k, ddf):         return lambda x: k * (k-1) * coeff * pow(x, k-2) + ddf(x)       # Define the polynomial and its first and second derivatives.     f = lambda x: 0     df = lambda x: 0     ddf = lambda x: 0     for k, coeff in enumerate(c):         # Actually it's a recursive call. It's a little bit different cause it's from bottom to top         # as this statement processes, f updates ( and a new lambda func is defined every time this statement executed)         f = add_fn(coeff, k, f)         if k > 0:             df = add_dfn(coeff, k, df)         if k > 1:             ddf = add_ddfn(coeff, k, ddf)      # Find as many extreme points as we can using Newton's method     lower, upper = lower_bound(x), upper_bound(x)     num_steps = 20     step = (upper - lower) / num_steps     starts = [lower + k * step for k in range(num_steps)]     extremums = [find_zero(df, ddf, n) for n in starts]      # Filter for the interval x and return     ns = [n for n in extremums if n > lower and n < upper] + [lower, upper]     values = [f(n) for n in ns]     return interval(min(values), max(values))                  
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-13 04:46:03 | 只看该作者
全局:
  1. 做完了hw05, extra的最后一题不太会 看的答案才懂得[code]def tree(label, branches=[]):
  2.     """Construct a tree with the given label value and a list of branches."""
  3.     for branch in branches:
  4.         assert is_tree(branch), 'branches must be trees'
  5.     return [label] + list(branches)

  6. def label(tree):
  7.     """Return the label value of a tree."""
  8.     return tree[0]

  9. def branches(tree):
  10.     """Return the list of branches of the given tree."""
  11.     return tree[1:]

  12. def is_tree(tree):
  13.     """Returns True if the given tree is a tree, and False otherwise."""
  14.     if type(tree) != list or len(tree) < 1:
  15.         return False
  16.     for branch in branches(tree):
  17.         if not is_tree(branch):
  18.             return False
  19.     return True

  20. def is_leaf(tree):
  21.     """Returns True if the given tree's list of branches is empty, and False
  22.     otherwise.
  23.     """
  24.     return not branches(tree)

  25. def print_tree(t, indent=0):
  26.     """Print a representation of this tree in which each node is
  27.     indented by two spaces times its depth from the root.

  28.     >>> print_tree(tree(1))
  29.     1
  30.     >>> print_tree(tree(1, [tree(2)]))
  31.     1
  32.       2
  33.     >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
  34.     >>> print_tree(numbers)
  35.     1
  36.       2
  37.       3
  38.         4
  39.         5
  40.       6
  41.         7
  42.     """
  43.     print('  ' * indent + str(label(t)))
  44.     for b in branches(t):
  45.         print_tree(b, indent + 1)

  46. def copy_tree(t):
  47.     """Returns a copy of t. Only for testing purposes.

  48.     >>> t = tree(5)
  49.     >>> copy = copy_tree(t)
  50.     >>> t = tree(6)
  51.     >>> print_tree(copy)
  52.     5
  53.     """
  54.     return tree(label(t), [copy_tree(b) for b in branches(t)])

  55. #############
  56. # Questions #
  57. #############

  58. def replace_leaf(t, old, new):
  59.     """Returns a new tree where every leaf value equal to old has
  60.     been replaced with new.

  61.     >>> yggdrasil = tree('odin',
  62.     ...                  [tree('balder',
  63.     ...                        [tree('thor'),
  64.     ...                         tree('loki')]),
  65.     ...                   tree('frigg',
  66.     ...                        [tree('thor')]),
  67.     ...                   tree('thor',
  68.     ...                        [tree('sif'),
  69.     ...                         tree('thor')]),
  70.     ...                   tree('thor')])
  71.     >>> laerad = copy_tree(yggdrasil) # copy yggdrasil for testing purposes
  72.     >>> print_tree(replace_leaf(yggdrasil, 'thor', 'freya'))
  73.     odin
  74.       balder
  75.         freya
  76.         loki
  77.       frigg
  78.         freya
  79.       thor
  80.         sif
  81.         freya
  82.       freya
  83.     >>> laerad == yggdrasil # Make sure original tree is unmodified
  84.     True
  85.     """
  86.     "*** YOUR CODE HERE ***"
  87.     if is_leaf(t):
  88.         if label(t) == old:
  89.             return tree(new)
  90.         else:
  91.             return t
  92.     else:
  93.         new_branches = [replace_leaf(b, old, new) for b in branches(t)]
  94.         return tree(label(t), new_branches)

  95. def print_move(origin, destination):
  96.     """Print instructions to move a disk."""
  97.     print("Move the top disk from rod", origin, "to rod", destination)

  98. def move_stack(n, start, end):
  99.     """Print the moves required to move n disks on the start pole to the end
  100.     pole without violating the rules of Towers of Hanoi.

  101.     n -- number of disks
  102.     start -- a pole position, either 1, 2, or 3
  103.     end -- a pole position, either 1, 2, or 3

  104.     There are exactly three poles, and start and end must be different. Assume
  105.     that the start pole has at least n disks of increasing size, and the end
  106.     pole is either empty or has a top disk larger than the top n start disks.

  107.     >>> move_stack(1, 1, 3)
  108.     Move the top disk from rod 1 to rod 3
  109.     >>> move_stack(2, 1, 3)
  110.     Move the top disk from rod 1 to rod 2
  111.     Move the top disk from rod 1 to rod 3
  112.     Move the top disk from rod 2 to rod 3
  113.     >>> move_stack(3, 1, 3)
  114.     Move the top disk from rod 1 to rod 3
  115.     Move the top disk from rod 1 to rod 2
  116.     Move the top disk from rod 3 to rod 2
  117.     Move the top disk from rod 1 to rod 3
  118.     Move the top disk from rod 2 to rod 1
  119.     Move the top disk from rod 2 to rod 3
  120.     Move the top disk from rod 1 to rod 3
  121.     """
  122.     assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
  123.     "*** YOUR CODE HERE ***"
  124.    
  125.     if n == 1:
  126.         print_move(start, end)
  127.     else:
  128.         ## The sum of three rods is 6 (1, 2, 3)
  129.         mid = 6 - start - end
  130.         move_stack(n-1, start, mid)
  131.         print_move(start, end)
  132.         move_stack(n-1, mid, end)
  133.    
  134.    
  135.    
  136.    
  137.    

  138. ###########
  139. # Mobiles #
  140. ###########

  141. def mobile(left, right):
  142.     """Construct a mobile from a left side and a right side."""
  143.     return tree('mobile', [left, right])

  144. def is_mobile(m):
  145.     return is_tree(m) and label(m) == 'mobile'

  146. def sides(m):
  147.     """Select the sides of a mobile."""
  148.     assert is_mobile(m), "must call sides on a mobile"
  149.     return branches(m)

  150. def is_side(m):
  151.     return not is_mobile(m) and not is_weight(m) and type(label(m)) == int

  152. def side(length, mobile_or_weight):
  153.     """Construct a side: a length of rod with a mobile or weight at the end."""
  154.     return tree(length, [mobile_or_weight])

  155. def length(s):
  156.     """Select the length of a side."""
  157.     assert is_side(s), "must call length on a side"
  158.     return label(s)

  159. def end(s):
  160.     """Select the mobile or weight hanging at the end of a side."""
  161.     assert is_side(s), "must call end on a side"
  162.     return branches(s)[0]

  163. def weight(size):
  164.     """Construct a weight of some size."""
  165.     assert size > 0
  166.     "*** YOUR CODE HERE ***"
  167.     return tree(size, [])
  168.    
  169. def size(w):
  170.     """Select the size of a weight."""
  171.     "*** YOUR CODE HERE ***"
  172.     return label(w)

  173. def is_weight(w):
  174.     """Whether w is a weight, not a mobile."""
  175.     "*** YOUR CODE HERE ***"
  176.     if is_leaf(w):
  177.         return True
  178.     else:
  179.         return False

  180. def examples():
  181.     t = mobile(side(1, weight(2)),
  182.                side(2, weight(1)))
  183.     u = mobile(side(5, weight(1)),
  184.                side(1, mobile(side(2, weight(3)),
  185.                               side(3, weight(2)))))
  186.     v = mobile(side(4, t), side(2, u))
  187.     return (t, u, v)


  188. def total_weight(m):
  189.     """Return the total weight of m, a weight or mobile.

  190.     >>> t, u, v = examples()
  191.     >>> total_weight(t)
  192.     3
  193.     >>> total_weight(u)
  194.     6
  195.     >>> total_weight(v)
  196.     9
  197.     """
  198.     if is_weight(m):
  199.         return size(m)
  200.     else:
  201.         assert is_mobile(m), "must get total weight of a mobile or a weight"
  202.         return sum([total_weight(end(s)) for s in sides(m)])











  203. def balanced(m):
  204.     """Return whether m is balanced.

  205.     >>> t, u, v = examples()
  206.     >>> balanced(t)
  207.     True
  208.     >>> balanced(v)
  209.     True
  210.     >>> w = mobile(side(3, t), side(2, u))
  211.     >>> balanced(w)
  212.     False
  213.     >>> balanced(mobile(side(1, v), side(1, w)))
  214.     False
  215.     >>> balanced(mobile(side(1, w), side(1, v)))
  216.     False
  217.     """
  218.     "*** YOUR CODE HERE ***"
  219.     ## 若第一次两边不balanced 直接false
  220.     if is_weight(m):
  221.         return True
  222.     elif length(sides(m)[0]) * total_weight(end(sides(m)[0])) != length(sides(m)[1]) * total_weight(end(sides(m)[1])):
  223.         return False
  224.     ## 若不为 weight,就扔进balanced函数中检测一遍。
  225.     else:
  226.         if_balanced = [balanced(end(x)) for x in sides(m)]
  227.         return all(if_balanced)
  228.         
  229. #    ### 其他人的答案d
  230. #    if is_weight(m):
  231. #        return True
  232. #    else:
  233. #        b = [balanced(end(s)) for s in sides(m)]
  234. #        weights = [total_weight(end(s)) for s in sides(m)]
  235. #        lengths = [length(s) for s in sides(m)]
  236. #        
  237. #        return all(b) and len(set(a * b for a, b in zip(lengths, weights))) == 1

  238. #######
  239. # OOP #
  240. #######

  241. class Account:
  242.     """An account has a balance and a holder.

  243.     >>> a = Account('John')
  244.     >>> a.deposit(10)
  245.     10
  246.     >>> a.balance
  247.     10
  248.     >>> a.interest
  249.     0.02

  250.     >>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404
  251.     2
  252.     >>> a.balance               # balance should not change
  253.     10
  254.     >>> a.time_to_retire(11)    # 10 -> 10.2 -> ... -> 11.040808032
  255.     5
  256.     >>> a.time_to_retire(100)
  257.     117
  258.     """

  259.     interest = 0.02  # A class attribute

  260.     def __init__(self, account_holder):
  261.         self.holder = account_holder
  262.         self.balance = 0

  263.     def deposit(self, amount):
  264.         """Add amount to balance."""
  265.         self.balance = self.balance + amount
  266.         return self.balance

  267.     def withdraw(self, amount):
  268.         """Subtract amount from balance if funds are available."""
  269.         if amount > self.balance:
  270.             return 'Insufficient funds'
  271.         self.balance = self.balance - amount
  272.         return self.balance

  273.     def time_to_retire(self, amount):
  274.         """Return the number of years until balance would grow to amount."""
  275.         assert self.balance > 0 and amount > 0 and self.interest > 0
  276.         "*** YOUR CODE HERE ***"
  277.         year = 0
  278.         total = self.balance
  279.         while total < amount:
  280.             total = total + total * self.interest
  281.             year += 1
  282.         return year

  283. class FreeChecking(Account):
  284.     """A bank account that charges for withdrawals, but the first two are free!

  285.     >>> ch = FreeChecking('Jack')
  286.     >>> ch.balance = 20
  287.     >>> ch.withdraw(100)  # First one's free
  288.     'Insufficient funds'
  289.     >>> ch.withdraw(3)    # And the second
  290.     17
  291.     >>> ch.balance
  292.     17
  293.     >>> ch.withdraw(3)    # Ok, two free withdrawals is enough
  294.     13
  295.     >>> ch.withdraw(3)
  296.     9
  297.     >>> ch2 = FreeChecking('John')
  298.     >>> ch2.balance = 10
  299.     >>> ch2.withdraw(3) # No fee
  300.     7
  301.     >>> ch.withdraw(3)  # ch still charges a fee
  302.     5
  303.     >>> ch.withdraw(5)  # Not enough to cover fee + withdraw
  304.     'Insufficient funds'
  305.     """
  306.     withdraw_fee = 1
  307.     free_withdrawals = 2

  308.     "*** YOUR CODE HERE ***"
  309.     def withdraw(self, amount):
  310.         if self.free_withdrawals > 0:
  311.             self.free_withdrawals -= 1
  312.             return Account.withdraw(self, amount)
  313.         else:
  314.             return Account.withdraw(self, amount + self.withdraw_fee)
  315.    
  316.    

  317. ############
  318. # Mutation #
  319. ############
  320. ### 这道还是不会。。。
  321. def make_counter():
  322.     """Return a counter function.

  323.     >>> c = make_counter()
  324.     >>> c('a')
  325.     1
  326.     >>> c('a')
  327.     2
  328.     >>> c('b')
  329.     1
  330.     >>> c('a')
  331.     3
  332.     >>> c2 = make_counter()
  333.     >>> c2('b')
  334.     1
  335.     >>> c2('b')
  336.     2
  337.     >>> c('b') + c2('b')
  338.     5
  339.     """
  340.     "*** YOUR CODE HERE ***"
  341.     str_dict = {}
  342.     def count(string):
  343.         nonlocal str_dict
  344.         if string in str_dict:
  345.             str_dict[string] += 1
  346.             return str_dict[string]
  347.         else:
  348.             str_dict[string] = 1
  349.             return str_dict[string]
  350.     return count
  351.             
  352.         
  353.    

  354. def make_fib():
  355.     """Returns a function that returns the next Fibonacci number
  356.     every time it is called.

  357.     >>> fib = make_fib()
  358.     >>> fib()
  359.     0
  360.     >>> fib()
  361.     1
  362.     >>> fib()
  363.     1
  364.     >>> fib()
  365.     2
  366.     >>> fib()
  367.     3
  368.     >>> fib2 = make_fib()
  369.     >>> fib() + sum([fib2() for _ in range(5)])
  370.     12
  371.     """
  372.     "*** YOUR CODE HERE ***"
  373.     curr = 1
  374.     prev = 0
  375.     n = 1
  376.     def fib():
  377.         nonlocal curr, prev, n
  378.         if n == 1:
  379.             n += 1
  380.             return prev
  381.         elif n == 2:
  382.             n += 1
  383.             return curr
  384.         else:
  385.             n += 1
  386.             curr, prev = curr + prev, curr
  387.             return curr
  388.     return fib
  389.         

  390. def make_withdraw(balance, password):
  391.     """Return a password-protected withdraw function.

  392.     >>> w = make_withdraw(100, 'hax0r')
  393.     >>> w(25, 'hax0r')
  394.     75
  395.     >>> error = w(90, 'hax0r')
  396.     >>> error
  397.     'Insufficient funds'
  398.     >>> error = w(25, 'hwat')
  399.     >>> error
  400.     'Incorrect password'
  401.     >>> new_bal = w(25, 'hax0r')
  402.     >>> new
  403.     50
  404.     >>> w(75, 'a')
  405.     'Incorrect password'
  406.     >>> w(10, 'hax0r')
  407.     40
  408.     >>> w(20, 'n00b')
  409.     'Incorrect password'
  410.     >>> w(10, 'hax0r')
  411.     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"
  412.     >>> w(10, 'l33t')
  413.     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"
  414.     >>> type(w(10, 'l33t')) == str
  415.     True
  416.     """
  417.     "*** YOUR CODE HERE ***"
  418.     password_try = 3
  419.     password_lst = []
  420.     def withdraw(amount, input_password):
  421.         nonlocal password_try, password_lst, balance
  422.         
  423.         if password_try == 0:
  424.             return "Your account is locked. Attempts: " + str(password_lst)
  425.         
  426.         if input_password != password:
  427.             password_try -= 1
  428.             password_lst.append(input_password)
  429.             return 'Incorrect password'
  430.         
  431.         if amount > balance:
  432.             return 'Insufficient funds'
  433.         else:
  434.             balance = balance - amount
  435.             return balance
  436.         
  437.     return withdraw
  438.    
  439.    
  440.    

  441. def make_joint(withdraw, old_password, new_password):
  442.     """Return a password-protected withdraw function that has joint access to
  443.     the balance of withdraw.

  444.     >>> w = make_withdraw(100, 'hax0r')
  445.     >>> w(25, 'hax0r')
  446.     75
  447.     >>> make_joint(w, 'my', 'secret')
  448.     'Incorrect password'
  449.     >>> j = make_joint(w, 'hax0r', 'secret')
  450.     >>> w(25, 'secret')
  451.     'Incorrect password'
  452.     >>> j(25, 'secret')
  453.     50
  454.     >>> j(25, 'hax0r')
  455.     25
  456.     >>> j(100, 'secret')
  457.     'Insufficient funds'

  458.     >>> j2 = make_joint(j, 'secret', 'code')
  459.     >>> j2(5, 'code')
  460.     20
  461.     >>> j2(5, 'secret')
  462.     15
  463.     >>> j2(5, 'hax0r')
  464.     10

  465.     >>> j2(25, 'password')
  466.     'Incorrect password'
  467.     >>> j2(5, 'secret')
  468.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  469.     >>> j(5, 'secret')
  470.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  471.     >>> w(5, 'hax0r')
  472.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  473.     >>> make_joint(w, 'hax0r', 'hello')
  474.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  475.     """
  476.     "*** YOUR CODE HERE ***"
  477.     ### 自己这道题不会做= =,难受。
  478.     w = withdraw(0, old_password)
  479.     if type(w) == str:
  480.         return w
  481.    
  482.     def joint_withdraw(amount, password):
  483.         if password == new_password or password == old_password:
  484.             return withdraw(amount, old_password)
  485.         else:
  486.             return withdraw(amount, password)
  487.         
  488.     return joint_withdraw                                                                                 
  489.    
  490.    
  491.    

  492. ###################
  493. # Extra Questions #
  494. ###################

  495. def interval(a, b):
  496.     """Construct an interval from a to b."""
  497.     return [a, b]

  498. def lower_bound(x):
  499.     """Return the lower bound of interval x."""
  500.     "*** YOUR CODE HERE ***"
  501.     return x[0]

  502. def upper_bound(x):
  503.     """Return the upper bound of interval x."""
  504.     "*** YOUR CODE HERE ***"
  505.     return x[1]

  506. def str_interval(x):
  507.     """Return a string representation of interval x."""
  508.     return '{0} to {1}'.format(lower_bound(x), upper_bound(x))

  509. def add_interval(x, y):
  510.     """Return an interval that contains the sum of any value in interval x and
  511.     any value in interval y."""
  512.     lower = lower_bound(x) + lower_bound(y)
  513.     upper = upper_bound(x) + upper_bound(y)
  514.     return interval(lower, upper)

  515. def mul_interval(x, y):
  516.     """Return the interval that contains the product of any value in x and any
  517.     value in y."""
  518.     p1 = lower_bound(x) * lower_bound(y)
  519.     p2 = lower_bound(x) * upper_bound(y)
  520.     p3 = upper_bound(x) * lower_bound(y)
  521.     p4 = upper_bound(x) * upper_bound(y)
  522.     return interval(min(p1, p2, p3, p4), max(p1, p2, p3, p4))

  523. def sub_interval(x, y):
  524.     """Return the interval that contains the difference between any value in x
  525.     and any value in y."""
  526.     "*** YOUR CODE HERE ***"
  527.    
  528.     return interval(lower_bound(x) - upper_bound(y), upper_bound(x) - lower_bound(y))

  529. def div_interval(x, y):
  530.     """Return the interval that contains the quotient of any value in x divided by
  531.     any value in y. Division is implemented as the multiplication of x by the
  532.     reciprocal of y."""
  533.     "*** YOUR CODE HERE ***"
  534.     assert lower_bound(y) * upper_bound(y) > 0
  535.     reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))
  536.     return mul_interval(x, reciprocal_y)

  537. def par1(r1, r2):
  538.     return div_interval(mul_interval(r1, r2), add_interval(r1, r2))

  539. def par2(r1, r2):
  540.     one = interval(1, 1)
  541.     rep_r1 = div_interval(one, r1)
  542.     rep_r2 = div_interval(one, r2)
  543.     return div_interval(one, add_interval(rep_r1, rep_r2))

  544. def check_par():
  545.     """Return two intervals that give different results for parallel resistors.

  546.     >>> r1, r2 = check_par()
  547.     >>> x = par1(r1, r2)
  548.     >>> y = par2(r1, r2)
  549.     >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)
  550.     True
  551.     """
  552.    
  553.     r1 = interval(-2, -1) # Replace this line!
  554.     r2 = interval(3, 4) # Replace this line!
  555.     return r1, r2

  556. def multiple_references_explanation():
  557.     return """The multiple reference problem...
  558.     par2 is a better method since it uses less functions like add, div sub, thus
  559.     creating less uncertainty compared with par1"""



  560. def quadratic(x, a, b, c):
  561.     """Return the interval that is the range of the quadratic defined by
  562.     coefficients a, b, and c, for domain interval x.

  563.     >>> str_interval(quadratic(interval(0, 2), -2, 3, -1))
  564.     '-3 to 0.125'
  565.     >>> str_interval(quadratic(interval(1, 3), 2, -3, 1))
  566.     '0 to 10'
  567.     """
  568.     "*** YOUR CODE HERE ***"
  569.     extreme = -b/a/2
  570.     l = lower_bound(x)
  571.     u = upper_bound(x)
  572.     if l > extreme or u < extreme:
  573.         low = min(a*l*l + b*l + c, a*u*u + b*u + c)
  574.         high = max(a*l*l + b*l + c, a*u*u + b*u + c)
  575.     else:
  576.         low = min(a*l*l + b*l + c, a*u*u + b*u + c, a*extreme*extreme + b*extreme + c)
  577.         high = max(a*l*l + b*l + c, a*u*u + b*u + c, a*extreme*extreme + b*extreme + c)
  578.     return interval(low, high)
  579.         


  580. # Official solution

  581. def polynomial(x, c):
  582.     """Return the interval that is the range of the polynomial defined by
  583.     coefficients c, for domain interval x.
  584.     >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))
  585.     '-3 to 0.125'
  586.     >>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))
  587.     '0 to 10'
  588.     >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))
  589.     '18.0 to 23.0'
  590.     """
  591.     # Newton's method from lecture

  592.     def improve(update, close, guess=1, max_updates=100):
  593.         """Iteratively improve guess with update until close(guess) is true or
  594.         max_updates have been applied."""
  595.         k = 0
  596.         while not close(guess) and k < max_updates:
  597.             guess = update(guess)
  598.             k = k + 1
  599.         return guess
  600.         
  601.     def approx_eq(x, y, tolerance=1e-15):
  602.         return abs(x - y) < tolerance
  603.             
  604.     def find_zero(f, df, guess=1):
  605.         """Return a zero of the function f with derivative df."""
  606.         def near_zero(x):
  607.             return approx_eq(f(x), 0)
  608.         return improve(newton_update(f, df), near_zero, guess)
  609.         
  610.     def newton_update(f, df):
  611.         """Return an update function for f with derivative df,
  612.         using Newton's method."""
  613.         def update(x):
  614.             return x - f(x) / df(x)
  615.         return update
  616.    
  617.    
  618.    
  619.     def add_fn(coeff, k, f):
  620.         return lambda x: coeff * pow(x, k) + f(x)

  621.     def add_dfn(coeff, k, df):
  622.         return lambda x: k * coeff * pow(x, k-1) + df(x)

  623.     def add_ddfn(coeff, k, ddf):
  624.         return lambda x: k * (k-1) * coeff * pow(x, k-2) + ddf(x)


  625.     # Define the polynomial and its first and second derivatives.
  626.     f = lambda x: 0
  627.     df = lambda x: 0
  628.     ddf = lambda x: 0
  629.     for k, coeff in enumerate(c):
  630.         # Actually it's a recursive call. It's a little bit different cause it's from bottom to top
  631.         # as this statement processes, f updates ( and a new lambda func is defined every time this statement executed)
  632.         f = add_fn(coeff, k, f)
  633.         if k > 0:
  634.             df = add_dfn(coeff, k, df)
  635.         if k > 1:
  636.             ddf = add_ddfn(coeff, k, ddf)

  637.     # Find as many extreme points as we can using Newton's method
  638.     lower, upper = lower_bound(x), upper_bound(x)
  639.     num_steps = 20
  640.     step = (upper - lower) / num_steps
  641.     starts = [lower + k * step for k in range(num_steps)]
  642.     extremums = [find_zero(df, ddf, n) for n in starts]

  643.     # Filter for the interval x and return
  644.     ns = [n for n in extremums if n > lower and n < upper] + [lower, upper]
  645.     values = [f(n) for n in ns]
  646.     return interval(min(values), max(values))


  647.    
  648.    
  649.    

复制代码
[/code]
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-13 10:08:32 | 只看该作者
全局:
lab06
  1. # A "simple" adventure game.

  2. class Player(object):
  3.     def __init__(self, name, place):
  4.         """Create a player object."""
  5.         self.name = name
  6.         self.place = place
  7.         ## creat an empty list of backpack
  8.         self.backpack = []

  9.     def look(self):
  10.         self.place.look()

  11.     def go_to(self, location):
  12.         """Go to a location if it's among the exits of player's current place.

  13.         >>> sather_gate = Place('Sather Gate', 'Sather Gate', [], [])
  14.         >>> gbc = Place('GBC', 'Golden Bear Cafe', [], [])
  15.         >>> sather_gate.add_exits([gbc])
  16.         >>> sather_gate.locked = True
  17.         >>> gbc.add_exits([sather_gate])
  18.         >>> me = Player('player', sather_gate)
  19.         >>> me.go_to('GBC')
  20.         You are at GBC
  21.         >>> me.place is gbc
  22.         True
  23.         >>> me.place.name
  24.         'GBC'
  25.         >>> me.go_to('GBC')
  26.         Can't go to GBC from GBC.
  27.         Try looking around to see where to go.
  28.         You are at GBC
  29.         >>> me.go_to('Sather Gate')
  30.         Sather Gate is locked! Go look for a key to unlock it
  31.         You are at GBC
  32.         """
  33.         destination_place = self.place.get_neighbor(location)
  34.         if destination_place.locked:
  35.             print(destination_place.name, 'is locked! Go look for a key to unlock it')
  36.         else:
  37.             self.place = destination_place
  38.         print('You are at ' + str(self.place.name))


  39.     def talk_to(self, person):
  40.         """Talk to person if person is at player's current place.

  41.         >>> jerry = Character('Jerry', 'I am not the Jerry you are looking for.')
  42.         >>> wheeler = Place('Wheeler', 'You are at Wheeler', [jerry], [])
  43.         >>> me = Player('player', wheeler)
  44.         >>> me.talk_to(jerry)
  45.         Person has to be a string.
  46.         >>> me.talk_to('Jerry')
  47.         Jerry says: I am not the Jerry you are looking for.
  48.         >>> me.talk_to('Tiffany')
  49.         Tiffany is not here.
  50.         """
  51.         if type(person) != str:
  52.             print('Person has to be a string.')
  53.         elif person in self.place.characters:
  54.             print(person, 'says:', self.place.characters[person].talk())
  55.         else:
  56.             print(person, 'is not here.')
  57.             
  58.    


  59.     def take(self, thing):
  60.         """Take a thing if thing is at player's current place

  61.         >>> lemon = Thing('Lemon', 'A lemon-looking lemon')
  62.         >>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [lemon])
  63.         >>> me = Player('Player', gbc)
  64.         >>> me.backpack
  65.         []
  66.         >>> me.take(lemon)
  67.         Thing should be a string.
  68.         >>> me.take('orange')
  69.         orange is not here.
  70.         >>> me.take('Lemon')
  71.         Player takes the Lemon
  72.         >>> me.take('Lemon')
  73.         Lemon is not here.
  74.         >>> isinstance(me.backpack[0], Thing)
  75.         True
  76.         >>> len(me.backpack)
  77.         1
  78.         """
  79.         if type(thing) != str:
  80.             print('Thing should be a string.')
  81.         elif thing in self.place.things:
  82.             taken = self.place.take(thing)
  83.             print(self.name, 'takes the', taken.name)
  84.             self.backpack.append(taken)
  85.         else:
  86.             print(thing, 'is not here.')
  87.         

  88.     def check_backpack(self):
  89.         """Print each item with its description and return a list of item names.

  90.         >>> cookie = Thing('Cookie', 'A huge cookie')
  91.         >>> donut = Thing('Donut', 'A huge donut')
  92.         >>> cupcake = Thing('Cupcake', 'A huge cupcake')
  93.         >>> gbc = Place('GBC', 'You are at Golden Bear Cafe',
  94.         ...             [], [cookie, donut, cupcake])
  95.         >>> me = Player('Player', gbc)
  96.         >>> me.check_backpack()
  97.         In your backpack:
  98.             there is nothing.
  99.         []
  100.         >>> me.take('Cookie')
  101.         Player takes the Cookie
  102.         >>> me.check_backpack()
  103.         In your backpack:
  104.             Cookie - A huge cookie
  105.         ['Cookie']
  106.         >>> me.take('Donut')
  107.         Player takes the Donut
  108.         >>> food = me.check_backpack()
  109.         In your backpack:
  110.             Cookie - A huge cookie
  111.             Donut - A huge donut
  112.         >>> food
  113.         ['Cookie', 'Donut']
  114.         """
  115.         print('In your backpack:')
  116.         if not self.backpack:
  117.             print('    there is nothing.')
  118.         else:
  119.             for item in self.backpack:
  120.                 print('   ', item.name, '-', item.description)
  121.         return [item.name for item in self.backpack]

  122.     def unlock(self, place):
  123.         """If player has a key, unlock a locked neighboring place.

  124.         >>> key = Key('SkeletonKey', 'A Key to unlock all doors.')
  125.         >>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [key])
  126.         >>> fsm = Place('FSM', 'Home of the nectar of the gods', [], [])
  127.         >>> gbc.add_exits([fsm])
  128.         >>> fsm.locked = True
  129.         >>> me = Player('Player', gbc)
  130.         >>> me.unlock(fsm)
  131.         Place must be a string
  132.         >>> me.go_to('FSM')
  133.         FSM is locked! Go look for a key to unlock it
  134.         You are at GBC
  135.         >>> me.unlock(fsm)
  136.         Place must be a string
  137.         >>> me.unlock('FSM')
  138.         FSM can't be unlocked without a key!
  139.         >>> me.take('SkeletonKey')
  140.         Player takes the SkeletonKey
  141.         >>> me.unlock('FSM')
  142.         FSM is now unlocked!
  143.         >>> me.unlock('FSM')
  144.         FSM is already unlocked!
  145.         >>> me.go_to('FSM')
  146.         You are at FSM
  147.         """
  148.         if type(place) != str:
  149.             print("Place must be a string")
  150.             return
  151.         key = None
  152.         for item in self.backpack:
  153.             if type(item) == Key:
  154.                 key = item
  155.         "*** YOUR CODE HERE ***"
  156.         next_place = self.place.get_neighbor(place)
  157.         if next_place.locked == False:
  158.             print(place, 'is already unlocked!')
  159.         elif key:
  160.             key.use(next_place)
  161.             print(place, 'is now unlocked!')
  162.         else:
  163.             print(place, "can't be unlocked without a key!")
  164.         


  165. class Character(object):
  166.     def __init__(self, name, message):
  167.         self.name = name
  168.         self.message = message

  169.     def talk(self):
  170.         return self.message


  171. class Thing(object):
  172.     def __init__(self, name, description):
  173.         self.name = name
  174.         self.description = description

  175.     def use(self, place):
  176.         print("You can't use a {0} here".format(self.name))

  177. """ Implement Key here! """
  178. class Key(Thing):
  179.     def use(self, place):
  180.         place.locked = False


  181. class Treasure(Thing):
  182.     def __init__(self, name, description, value, weight):
  183.         Thing.__init__(self, name, description)
  184.         self.value = value
  185.         self.weight = weight

  186. class Place(object):
  187.     def __init__(self, name, description, characters, things):
  188.         self.name = name
  189.         self.description = description
  190.         self.characters = {character.name: character for character in characters}
  191.         self.things = {thing.name: thing for thing in things}
  192.         self.locked = False
  193.         self.exits = {} # {'name': (exit, 'description')}

  194.     def look(self):
  195.         print('You are currently at ' + self.name + '. You take a look around and see:')
  196.         print('Characters:')
  197.         if not self.characters:
  198.             print('    no one in particular')
  199.         else:
  200.             for character in self.characters:
  201.                 print('   ', character)
  202.         print('Things:')
  203.         if not self.things:
  204.             print('    nothing in particular')
  205.         else:
  206.             for thing in self.things.values():
  207.                 print('   ', thing.name, '-', thing.description)
  208.         self.check_exits()

  209.     def get_neighbor(self, exit):
  210.         """
  211.         >>> sather_gate = Place('Sather Gate', 'You are at Sather Gate', [], [])
  212.         >>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [])
  213.         >>> gbc.add_exits([sather_gate])
  214.         >>> place = gbc.get_neighbor('Sather Gate')
  215.         >>> place is sather_gate
  216.         True
  217.         >>> place = gbc.get_neighbor('FSM')
  218.         Can't go to FSM from GBC.
  219.         Try looking around to see where to go.
  220.         >>> place is gbc
  221.         True
  222.         """
  223.         if type(exit) != str:
  224.             print('Exit has to be a string.')
  225.             return self
  226.         elif exit in self.exits:
  227.             exit_place = self.exits[exit][0]
  228.             return exit_place
  229.         else:
  230.             print("Can't go to {} from {}.".format(exit, self.name))
  231.             print("Try looking around to see where to go.")
  232.             return self

  233.     def take(self, thing):
  234.         return self.things.pop(thing)

  235.     def check_exits(self):
  236.         print('You can exit to:')
  237.         for exit in self.exits:
  238.             print('   ', exit)

  239.     def add_exits(self, places):
  240.         for place in places:
  241.             self.exits[place.name] = (place, place.description)


  242. """ Optional problems for Lab 6 """

  243. ## Nonlocal practice
  244. def vending_machine(snacks):
  245.     """Cycles through sequence of snacks.

  246.     >>> vender = vending_machine(('chips', 'chocolate', 'popcorn'))
  247.     >>> vender()
  248.     'chips'
  249.     >>> vender()
  250.     'chocolate'
  251.     >>> vender()
  252.     'popcorn'
  253.     >>> vender()
  254.     'chips'
  255.     >>> other = vending_machine(('brownie',))
  256.     >>> other()
  257.     'brownie'
  258.     >>> vender()
  259.     'chocolate'
  260.     """
  261.     "*** YOUR CODE HERE ***"
  262.     i = 0
  263.     def vender():
  264.         nonlocal i
  265.         i += 1
  266.         return snacks[(i-1) % 3]
  267.     return vender
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表