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

2018 Spring CS61a打卡与作业答案

🔗
 楼主| smoothiethu 2019-8-15 17:43:59 | 只看该作者
全局:
  1. Lab08 finished
  2. """ Lab 08: Midterm Review """

  3. # Linked lists
  4. def deep_len(lnk):
  5.     """ Returns the deep length of a possibly deep linked list.

  6.     >>> deep_len(Link(1, Link(2, Link(3))))
  7.     3
  8.     >>> deep_len(Link(Link(1, Link(2)), Link(3, Link(4))))
  9.     4
  10.     >>> levels = Link(Link(Link(1, Link(2)), \
  11.             Link(3)), Link(Link(4), Link(5)))
  12.     >>> print(levels)
  13.     <<<1 2> 3> <4> 5>
  14.     >>> deep_len(levels)
  15.     5
  16.     """
  17.     "*** YOUR CODE HERE ***"
  18. #    count = 0
  19. #    m = 0
  20. #    while lnk is not Link.empty:
  21. #        if not isinstance(lnk.first, Link):
  22. #            count += 1
  23. #            lnk = lnk.rest
  24. #        else:
  25. #            link = lnk.first
  26. #            while link is not Link.empty:
  27. #                if not isinstance(link.first, Link):
  28. #                    m += 1
  29. #                    link = link.rest
  30. #    return m + count
  31.     if lnk is Link.empty:
  32.         return 0
  33.     elif isinstance(lnk.first, Link):
  34.         return deep_len(lnk.first) + deep_len(lnk.rest)
  35.     else:
  36.         return 1 + deep_len(lnk.rest)
  37.    

  38. # Link class
  39. class Link:
  40.     """A linked list.

  41.     >>> s = Link(1)
  42.     >>> s.first
  43.     1
  44.     >>> s.rest is Link.empty
  45.     True
  46.     >>> s = Link(2, Link(3, Link(4)))
  47.     >>> s.second
  48.     3
  49.     >>> s.first = 5
  50.     >>> s.second = 6
  51.     >>> s.rest.rest = Link.empty
  52.     >>> s                                    # Displays the contents of repr(s)
  53.     Link(5, Link(6))
  54.     >>> s.rest = Link(7, Link(Link(8, Link(9))))
  55.     >>> s
  56.     Link(5, Link(7, Link(Link(8, Link(9)))))
  57.     >>> print(s)                             # Prints str(s)
  58.     <5 7 <8 9>>
  59.     """
  60.     empty = ()

  61.     def __init__(self, first, rest=empty):
  62.         assert rest is Link.empty or isinstance(rest, Link)
  63.         self.first = first
  64.         self.rest = rest

  65.     @property
  66.     def second(self):
  67.         return self.rest.first

  68.     @second.setter
  69.     def second(self, value):
  70.         self.rest.first = value


  71.     def __repr__(self):
  72.         if self.rest is not Link.empty:
  73.             rest_repr = ', ' + repr(self.rest)
  74.         else:
  75.             rest_repr = ''
  76.         return 'Link(' + repr(self.first) + rest_repr + ')'

  77.     def __str__(self):
  78.         string = '<'
  79.         while self.rest is not Link.empty:
  80.             string += str(self.first) + ' '
  81.             self = self.rest
  82.         return string + str(self.first) + '>'
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-15 17:44:26 | 只看该作者
全局:
Lab08 extra

  1. """ Extra questions for Lab 08 """

  2. from lab08 import *

  3. # OOP
  4. class Keyboard:
  5.     """A Keyboard takes in an arbitrary amount of buttons, and has a
  6.     dictionary of positions as keys, and values as Buttons.

  7.     >>> b1 = Button(0, "H")
  8.     >>> b2 = Button(1, "I")
  9.     >>> k = Keyboard(b1, b2)
  10.     >>> k.buttons[0].key
  11.     'H'
  12.     >>> k.press(1)
  13.     'I'
  14.     >>> k.typing([0, 1])
  15.     'HI'
  16.     >>> k.typing([1, 0])
  17.     'IH'
  18.     >>> b1.pressed
  19.     2
  20.     >>> b2.pressed
  21.     3
  22.     """

  23.     def __init__(self, *args):
  24.         "*** YOUR CODE HERE ***"
  25.         self.buttons = {button.pos: button for button in args}

  26.     def press(self, info):
  27.         """Takes in a position of the button pressed, and
  28.         returns that button's output"""
  29.         "*** YOUR CODE HERE ***"
  30.         self.buttons[info].pressed += 1
  31.         return self.buttons[info].key

  32.     def typing(self, typing_input):
  33.         """Takes in a list of positions of buttons pressed, and
  34.         returns the total output"""
  35.         "*** YOUR CODE HERE ***"
  36.         output = str()
  37.         for i in typing_input:
  38.             output += self.press(i)
  39.         return output
  40.             

  41. class Button:
  42.     def __init__(self, pos, key):
  43.         self.pos = pos
  44.         self.key = key
  45.         self.pressed = 0

  46. # Nonlocal
  47. def make_advanced_counter_maker():
  48.     """Makes a function that makes counters that understands the
  49.     messages "count", "global-count", "reset", and "global-reset".
  50.     See the examples below:

  51.     >>> make_counter = make_advanced_counter_maker()
  52.     >>> tom_counter = make_counter()
  53.     >>> tom_counter('count')
  54.     1
  55.     >>> tom_counter('count')
  56.     2
  57.     >>> tom_counter('global-count')
  58.     1
  59.     >>> jon_counter = make_counter()
  60.     >>> jon_counter('global-count')
  61.     2
  62.     >>> jon_counter('count')
  63.     1
  64.     >>> jon_counter('reset')
  65.     >>> jon_counter('count')
  66.     1
  67.     >>> tom_counter('count')
  68.     3
  69.     >>> jon_counter('global-count')
  70.     3
  71.     >>> jon_counter('global-reset')
  72.     >>> tom_counter('global-count')
  73.     1
  74.     """
  75.     "*** YOUR CODE HERE ***"
  76.     ## Official solution, didn't think of this myself.
  77.    
  78.     def make_counter():
  79.         def counter(message):
  80.             if message == 'count':
  81.                 counter.count += 1
  82.                 return counter.count
  83.             elif message == 'global-count':
  84.                 make_counter.global_count += 1
  85.                 return make_counter.global_count
  86.             elif message == 'reset':
  87.                 counter.count = 0
  88.                 return None
  89.             elif message == 'global-reset':
  90.                 make_counter.global_count = 0
  91.                 return None
  92.         counter.count = 0
  93.         return counter
  94.     make_counter.global_count = 0
  95.     return make_counter

  96. # Lists
  97. def trade(first, second):
  98.     """Exchange the smallest prefixes of first and second that have equal sum.

  99.     >>> a = [1, 1, 3, 2, 1, 1, 4]
  100.     >>> b = [4, 3, 2, 7]
  101.     >>> trade(a, b) # Trades 1+1+3+2=7 for 4+3=7
  102.     'Deal!'
  103.     >>> a
  104.     [4, 3, 1, 1, 4]
  105.     >>> b
  106.     [1, 1, 3, 2, 2, 7]
  107.     >>> c = [3, 3, 2, 4, 1]
  108.     >>> trade(b, c)
  109.     'No deal!'
  110.     >>> b
  111.     [1, 1, 3, 2, 2, 7]
  112.     >>> c
  113.     [3, 3, 2, 4, 1]
  114.     >>> trade(a, c)
  115.     'Deal!'
  116.     >>> a
  117.     [3, 3, 2, 1, 4]
  118.     >>> b
  119.     [1, 1, 3, 2, 2, 7]
  120.     >>> c
  121.     [4, 3, 1, 4, 1]
  122.     """
  123.     m, n = 1, 1
  124.     deal = False
  125.     "*** YOUR CODE HERE ***"
  126.     while m < len(first) and n < len(second):
  127.         if sum(first[:m]) == sum(second[:n]):
  128.             deal = True
  129.             break
  130.         elif sum(first[:m]) > sum(second[:n]):
  131.             n += 1
  132.         else:
  133.             m += 1
  134.    
  135.     if deal: # change this line!
  136.         first[:m], second[:n] = second[:n], first[:m]
  137.         return 'Deal!'
  138.     else:
  139.         return 'No deal!'

  140. # Recursive objects
  141. def make_to_string(front, mid, back, empty_repr):
  142.     """ Returns a function that turns linked lists to strings.

  143.     >>> kevins_to_string = make_to_string("[", "|-]-->", "", "[]")
  144.     >>> jerrys_to_string = make_to_string("(", " . ", ")", "()")
  145.     >>> lst = Link(1, Link(2, Link(3, Link(4))))
  146.     >>> kevins_to_string(lst)
  147.     '[1|-]-->[2|-]-->[3|-]-->[4|-]-->[]'
  148.     >>> kevins_to_string(Link.empty)
  149.     '[]'
  150.     >>> jerrys_to_string(lst)
  151.     '(1 . (2 . (3 . (4 . ()))))'
  152.     >>> jerrys_to_string(Link.empty)
  153.     '()'
  154.     """
  155.     "*** YOUR CODE HERE ***"
  156.     def convert(lst):
  157.         if lst is Link.empty:
  158.             return empty_repr
  159.         else:
  160.             output = str()
  161.             n = 0
  162.             while lst is not Link.empty:
  163.                 output = output + front + str(lst.first) + mid
  164.                 n += 1
  165.                 lst = lst.rest
  166.             output = output + empty_repr + back * n
  167.             return output      
  168.     return convert
  169.    
  170.    

  171. def tree_map(fn, t):
  172.     """Maps the function fn over the entries of t and returns the
  173.     result in a new tree.

  174.     >>> numbers = Tree(1,
  175.     ...                [Tree(2,
  176.     ...                      [Tree(3),
  177.     ...                       Tree(4)]),
  178.     ...                 Tree(5,
  179.     ...                      [Tree(6,
  180.     ...                            [Tree(7)]),
  181.     ...                       Tree(8)])])
  182.     >>> print(tree_map(lambda x: 2**x, numbers))
  183.     2
  184.       4
  185.         8
  186.         16
  187.       32
  188.         64
  189.           128
  190.         256
  191.     """
  192.     "*** YOUR CODE HERE ***"
  193.     if t.is_leaf():
  194.         return Tree(label = fn(t.label))
  195.     else:
  196.         label = fn(t.label)
  197.         new_branches = [tree_map(fn, b) for b in t.branches]
  198.         return Tree(label, new_branches)
  199.    
  200.    
  201.    

  202. def long_paths(tree, n):
  203.     """Return a list of all paths in tree with length at least n.

  204.     >>> t = Tree(3, [Tree(4), Tree(4), Tree(5)])
  205.     >>> left = Tree(1, [Tree(2), t])
  206.     >>> mid = Tree(6, [Tree(7, [Tree(8)]), Tree(9)])
  207.     >>> right = Tree(11, [Tree(12, [Tree(13, [Tree(14)])])])
  208.     >>> whole = Tree(0, [left, Tree(13), mid, right])
  209.     >>> for path in long_paths(whole, 2):
  210.     ...     print(path)
  211.     ...
  212.     <0 1 2>
  213.     <0 1 3 4>
  214.     <0 1 3 4>
  215.     <0 1 3 5>
  216.     <0 6 7 8>
  217.     <0 6 9>
  218.     <0 11 12 13 14>
  219.     >>> for path in long_paths(whole, 3):
  220.     ...     print(path)
  221.     ...
  222.     <0 1 3 4>
  223.     <0 1 3 4>
  224.     <0 1 3 5>
  225.     <0 6 7 8>
  226.     <0 11 12 13 14>
  227.     >>> long_paths(whole, 4)
  228.     [Link(0, Link(11, Link(12, Link(13, Link(14)))))]
  229.     """
  230.     "*** YOUR CODE HERE ***"
  231.     ### 看了别人的算法自己模仿着做的,需要理解停止条件为leaf并且n长度达到。
  232.     paths = []
  233.     if n <= 0 and tree.is_leaf():
  234.         paths.append(Link(tree.label))
  235.     for b in tree.branches:
  236.         for path in long_paths(b, n - 1):
  237.             paths.append(Link(tree.label, path))
  238.     return paths
  239.    
  240.    

  241. # Orders of Growth
  242. def zap(n):
  243.     i, count = 1, 0
  244.     while i <= n:
  245.         while i <= 5 * n:
  246.             count += i
  247.             print(i / 6)
  248.             i *= 3
  249.     return count

  250. def boom(n):
  251.     sum = 0
  252.     a, b = 1, 1
  253.     while a <= n*n:
  254.         while b <= n*n:
  255.             sum += (a*b)
  256.             b += 1
  257.         b = 0
  258.         a += 1
  259.     return sum

  260. # Tree class
  261. class Tree:
  262.     def __init__(self, label, branches=[]):
  263.         for c in branches:
  264.             assert isinstance(c, Tree)
  265.         self.label = label
  266.         self.branches = list(branches)

  267.     def __repr__(self):
  268.         if self.branches:
  269.             branches_str = ', ' + repr(self.branches)
  270.         else:
  271.             branches_str = ''
  272.         return 'Tree({0}{1})'.format(self.label, branches_str)

  273.     def is_leaf(self):
  274.         return not self.branches

  275.     def __eq__(self, other):
  276.         return type(other) is type(self) and self.label == other.label \
  277.                and self.branches == other.branches
  278.    
  279.     def __str__(self):
  280.         def print_tree(t, indent=0):
  281.             tree_str = '  ' * indent + str(t.label) + "\n"
  282.             for b in t.branches:
  283.                 tree_str += print_tree(b, indent + 1)
  284.             return tree_str
  285.         return print_tree(self).rstrip()

  286.     def copy_tree(self):
  287.         return Tree(self.label, [b.copy_tree() for b in self.branches])
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-16 15:41:06 | 只看该作者
全局:
今天终于上完了除了第三个chapter之外所有的课程,这周末把几次作业和lab做完,做做ants project,就可以正式开始cs61b和刷题啦
加油!
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-17 04:04:48 | 只看该作者
全局:
Lab 11
  1. """ Lab 11: Iterators and Generators """

  2. # Q1
  3. def scale(s, k):
  4.     """Yield elements of the iterable s scaled by a number k.

  5.     >>> s = scale([1, 5, 2], 5)
  6.     >>> type(s)
  7.     <class 'generator'>
  8.     >>> list(s)
  9.     [5, 25, 10]

  10.     >>> m = scale(naturals(), 2)
  11.     >>> [next(m) for _ in range(5)]
  12.     [2, 4, 6, 8, 10]
  13.     """
  14.     "*** YOUR CODE HERE ***"
  15. #    def gen():
  16. #        for i in s:
  17. #           yield i * k
  18. #    return gen()
  19.    
  20. ##  Official solution
  21. ##  用map function生成新的iterable
  22.     yield from map(lambda x: k * x, s)

  23. # Q2
  24. def trap(s, k):
  25.     """Return a generator that yields the first K values in iterable S,
  26.     but raises a ValueError exception if any more values are requested.

  27.     >>> t = trap([3, 2, 1], 2)
  28.     >>> next(t)
  29.     3
  30.     >>> next(t)
  31.     2
  32.     >>> next(t)
  33.     ValueError
  34.     >>> list(trap(range(5), 5))
  35.     ValueError
  36.     >>> t2 = trap(map(abs, reversed(range(-6, -4))), 2)
  37.     >>> next(t2)
  38.     5
  39.     >>> next(t2)
  40.     6
  41.     >>> next(t2)
  42.     ValueError
  43.     """
  44.     "*** YOUR CODE HERE ***"
  45.     s = iter(s)
  46.     while k > 0: ## 一共可以call k次
  47.         yield next(s)
  48.         k -= 1
  49.     raise ValueError
  50.    

  51. # the naturals generator is used for testing scale and merge functions
  52. def naturals():
  53.     """A generator function that yields the infinite sequence of natural
  54.     numbers, starting at 1.

  55.     >>> m = naturals()
  56.     >>> type(m)
  57.     <class 'generator'>
  58.     >>> [next(m) for _ in range(10)]
  59.     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  60.     """
  61.     i = 1
  62.     while True:
  63.         yield i
  64.         i += 1
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-17 07:06:57 | 只看该作者
全局:
  1. lab11 extra
  2. """ Optional Questions for Lab 11 """

  3. from lab11 import *

  4. # Q5
  5. def hailstone(n):
  6.     """
  7.     >>> for num in hailstone(10):
  8.     ...     print(num)
  9.     ...
  10.     10
  11.     5
  12.     16
  13.     8
  14.     4
  15.     2
  16.     1
  17.     """
  18.     "*** YOUR CODE HERE ***"
  19.     while n > 1:
  20.         if n % 2 == 0:
  21.             yield n
  22.             n = n // 2
  23.         else:
  24.             yield n
  25.             n = n*3 + 1
  26.     yield n         
  27.    
  28.    

  29. # Q6
  30. def repeated(t, k):
  31.     """Return the first value in iterable T that appears K times in a row.

  32.     >>> s = [3, 2, 1, 2, 1, 4, 4, 5, 5, 5]
  33.     >>> repeated(trap(s, 7), 2)
  34.     4
  35.     >>> repeated(trap(s, 10), 3)
  36.     5
  37.     >>> print(repeated([4, None, None, None], 3))
  38.     None
  39.     """
  40.     assert k > 1
  41.     "*** YOUR CODE HERE ***"
  42.     ## Get the unique list first
  43. #    unique_lst = []
  44. #    for x in t:
  45. #        if x not in unique_lst:
  46. #            unique_lst.append(x)
  47. #    for x in unique_lst:
  48. #        num = 0
  49. #        for i in t:
  50. #            if x == i:
  51. #                num += 1
  52. #            if num == k:
  53. #                return x
  54. #    return


  55.     ## Others' solution
  56.     t = iter(t)
  57.     count, prev = 1, next(t)
  58.     for item in t:
  59.         if item == prev:
  60.             count += 1
  61.             if count == k:
  62.                 return item
  63.         else:
  64.             count = 1
  65.         prev = item
  66.     return
  67.    
  68.    

  69. # Q7
  70. def merge(s0, s1):
  71.     """Yield the elements of strictly increasing iterables s0 and s1, removing
  72.     repeats. Assume that s0 and s1 have no repeats. s0 or s1 may be infinite
  73.     sequences.

  74.     >>> m = merge([0, 2, 4, 6, 8, 10, 12, 14], [0, 3, 6, 9, 12, 15])
  75.     >>> type(m)
  76.     <class 'generator'>
  77.     >>> list(m)
  78.     [0, 2, 3, 4, 6, 8, 9, 10, 12, 14, 15]
  79.     >>> def big(n):
  80.     ...    k = 0
  81.     ...    while True: yield k; k += n
  82.     >>> m = merge(big(2), big(3))
  83.     >>> [next(m) for _ in range(11)]
  84.     [0, 2, 3, 4, 6, 8, 9, 10, 12, 14, 15]
  85.     """
  86.     i0, i1 = iter(s0), iter(s1)
  87.     e0, e1 = next(i0, None), next(i1, None)
  88.     "*** YOUR CODE HERE ***"
  89.     while e0 != None and e1 != None:
  90.         if e0 < e1:
  91.             yield e0
  92.             e0 = next(i0, None)
  93.         elif e0 > e1:
  94.             yield e1
  95.             e1 = next(i1, None)
  96.         else:
  97.             yield e0
  98.             e0, e1 = next(i0, None), next(i1, None)
  99.     if e0 == None:
  100.         yield e1
  101.     else:
  102.         yield e0

  103. # Q8
  104. def remainders_generator(m):
  105.     """
  106.     Takes in an integer m, and yields m different remainder groups
  107.     of m.

  108.     >>> remainders_mod_four = remainders_generator(4)
  109.     >>> for rem_group in remainders_mod_four:
  110.     ...     for _ in range(3):
  111.     ...         print(next(rem_group))
  112.     0
  113.     4
  114.     8
  115.     1
  116.     5
  117.     9
  118.     2
  119.     6
  120.     10
  121.     3
  122.     7
  123.     11
  124.     """
  125.     "*** YOUR CODE HERE ***"
  126. #    for reminder in range(m):
  127. #        i = 0
  128. #        while i >= 0:
  129. #            yield i * m + reminder
  130. #            i += 1
  131.     ## Take k as an argument since for each different generator
  132.     ## the remainder is different, thus working as variable
  133.     def remainder(k):
  134.         i = 0
  135.         while i >= 0:
  136.             yield m * i + k
  137.             i += 1
  138.     for j in range(m):
  139.         yield remainder(j)
  140.    
  141.    

  142. # Q9
  143. def zip_generator(*iterables):
  144.     """
  145.     Takes in any number of iterables and zips them together.
  146.     Returns a generator that outputs a series of lists, each
  147.     containing the nth items of each iterable.
  148.     >>> z = zip_generator([1, 2, 3], [4, 5, 6], [7, 8])
  149.     >>> for i in z:
  150.     ...     print(i)
  151.     ...
  152.     [1, 4, 7]
  153.     [2, 5, 8]
  154.     """
  155.     "*** YOUR CODE HERE ***"
  156.    
  157.     t = zip(*iterables)
  158.     for gen in t:
  159.         yield list(gen)
  160.         
  161.     ## Other solution
  162.     iterators = [iter(i) for i in iterables]
  163.     while True:
  164.         try:
  165.             yield [next(i) for i in iterators]
  166.         except StopIteration:
  167.             break
  168.    
  169.    
  170.    
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-17 07:12:37 | 只看该作者
全局:
纠结了一会 还是不去管最后的SQL部分了,毕竟后面会单独去刷题目。
cs61a就差个最后的antproject 了,准备正式开始上cs61b。
加油!
回复

使用道具 举报

🔗
CharlesZKQ 2019-8-21 16:52:37 | 只看该作者
全局:
您好想请问一下,我做完了yelp map,代码验证都是对的,但是图加载不出来是什么情况?
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-21 17:36:55 | 只看该作者
全局:
CharlesZKQ 发表于 2019-8-21 16:52
您好想请问一下,我做完了yelp map,代码验证都是对的,但是图加载不出来是什么情况?

我也没有去尝试GUI,只是确认代码没问题就没去管了
回复

使用道具 举报

🔗
豆瓣酱喵 2019-12-22 14:53:09 | 只看该作者
全局:
请问一下CS61A 的评分系统怎么用啊?
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-12-22 17:50:23 | 只看该作者
全局:
豆瓣酱喵 发表于 2019-12-22 14:53
请问一下CS61A 的评分系统怎么用啊?

我没用他们的评分系统 我就是自己写几个test case看看。。
回复

使用道具 举报

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

本版积分规则

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