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

2018 Spring CS61a打卡与作业答案

🔗
 楼主| smoothiethu 2019-7-31 15:57:02 | 只看该作者
全局:
hw4
  1. HW_SOURCE_FILE = 'hw04.py'

  2. ###############
  3. #  Questions  #
  4. ###############

  5. def intersection(st, ave):
  6.     """Represent an intersection using the Cantor pairing function."""
  7.     return (st+ave)*(st+ave+1)//2 + ave

  8. def street(inter):
  9.     return w(inter) - avenue(inter)

  10. def avenue(inter):
  11.     return inter - (w(inter) ** 2 + w(inter)) // 2

  12. w = lambda z: int(((8*z+1)**0.5-1)/2)

  13. def taxicab(a, b):
  14.     """Return the taxicab distance between two intersections.

  15.     >>> times_square = intersection(46, 7)
  16.     >>> ess_a_bagel = intersection(51, 3)
  17.     >>> taxicab(times_square, ess_a_bagel)
  18.     9
  19.     >>> taxicab(ess_a_bagel, times_square)
  20.     9
  21.     """
  22.     "*** YOUR CODE HERE ***"

  23.     return abs(street(a) - street(b)) + abs(avenue(a) - avenue(b))
  24.    
  25.    
  26.    

  27. def squares(s):
  28.     """Returns a new list containing square roots of the elements of the
  29.     original list that are perfect squares.

  30.     >>> seq = [8, 49, 8, 9, 2, 1, 100, 102]
  31.     >>> squares(seq)
  32.     [7, 3, 1, 10]
  33.     >>> seq = [500, 30]
  34.     >>> squares(seq)
  35.     []
  36.     """
  37.     "*** YOUR CODE HERE ***"
  38.     from math import sqrt
  39.     output = []
  40.     for i in s:
  41.         if sqrt(i) == round(sqrt(i)):
  42.             output.append(sqrt(i))
  43.     return output
  44.         
  45. #   official solution
  46. #   return [round(n**0.5) for n in s if round(n**0.5) ** 2 == n]

  47. def g(n):
  48.     """Return the value of G(n), computed recursively.

  49.     >>> g(1)
  50.     1
  51.     >>> g(2)
  52.     2
  53.     >>> g(3)
  54.     3
  55.     >>> g(4)
  56.     10
  57.     >>> g(5)
  58.     22
  59.     >>> from construct_check import check
  60.     >>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
  61.     True
  62.     """
  63.     "*** YOUR CODE HERE ***"
  64.     if n == 1:
  65.         return 1
  66.     elif n == 2:
  67.         return 2
  68.     elif n == 3:
  69.         return 3
  70.     else:
  71.         return g(n-1) + 2 * g(n-2) + 3 * g(n-3)
  72.    
  73.    

  74. def g_iter(n):
  75.     """Return the value of G(n), computed iteratively.

  76.     >>> g_iter(1)
  77.     1
  78.     >>> g_iter(2)
  79.     2
  80.     >>> g_iter(3)
  81.     3
  82.     >>> g_iter(4)
  83.     10
  84.     >>> g_iter(5)
  85.     22
  86.     >>> from construct_check import check
  87.     >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
  88.     True
  89.     """
  90.     "*** YOUR CODE HERE ***"
  91.     # iteration method要找到更新的规律,用while来进行update。
  92.     if n <= 3:
  93.         return n
  94.     else:
  95.         num1, num2, num3 = 1, 2, 3
  96.         i = 3
  97.         while i < n:
  98.             num1, num2, num3 = num2, num3, 3 * num1 + 2 * num2 + num3
  99.             i += 1
  100.         return num3
  101.             
  102.    
  103.    

  104. def pingpong(n):
  105.     """Return the nth element of the ping-pong sequence.

  106.     >>> pingpong(7)
  107.     7
  108.     >>> pingpong(8)
  109.     6
  110.     >>> pingpong(15)
  111.     1
  112.     >>> pingpong(21)
  113.     -1
  114.     >>> pingpong(22)
  115.     0
  116.     >>> pingpong(30)
  117.     6
  118.     >>> pingpong(68)
  119.     2
  120.     >>> pingpong(69)
  121.     1
  122.     >>> pingpong(70)
  123.     0
  124.     >>> pingpong(71)
  125.     1
  126.     >>> pingpong(72)
  127.     0
  128.     >>> pingpong(100)
  129.     2
  130.     >>> from construct_check import check
  131.     >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
  132.     True
  133.     """
  134.     "*** YOUR CODE HERE ***"
  135.    
  136.     def make_switch(x):
  137.         if (has_seven(x)) or (x % 7 == 0):
  138.             return True
  139.         else:
  140.             return False
  141.    
  142.     def count(x, num, switch_indicator):
  143.         if x == n: # stopping critiria
  144.             return num
  145.         elif make_switch(x):
  146.             if switch_indicator % 2 == 0:
  147.                 return count(x + 1, num - 1, switch_indicator + 1)
  148.             else:
  149.                 return count(x + 1, num + 1, switch_indicator + 1)
  150.         else:
  151.             if switch_indicator % 2 == 0:
  152.                 return count(x + 1, num + 1, switch_indicator)
  153.             else:
  154.                 return count(x + 1, num - 1, switch_indicator)
  155.     return count(1, 1, 0)
  156.         

  157.    
  158.    
  159.    
  160. # Iteration method, but not okay in this question.
  161. #    i = 1
  162. #    output = 1
  163. #    multiplier = 1
  164. #    while i < n:
  165. #        if (has_seven(i)) or (i % 7 == 0):
  166. #            multiplier = multiplier * (-1)
  167. #        output = output + multiplier
  168. #        i += 1
  169. #            
  170. #    return output
  171.             
  172.    

  173. def has_seven(k):
  174.     """Returns True if at least one of the digits of k is a 7, False otherwise.

  175.     >>> has_seven(3)
  176.     False
  177.     >>> has_seven(7)
  178.     True
  179.     >>> has_seven(2734)
  180.     True
  181.     >>> has_seven(2634)
  182.     False
  183.     >>> has_seven(734)
  184.     True
  185.     >>> has_seven(7777)
  186.     True
  187.     """
  188.     if k % 10 == 7:
  189.         return True
  190.     elif k < 10:
  191.         return False
  192.     else:
  193.         return has_seven(k // 10)

  194. def count_change(amount):
  195.     """Return the number of ways to make change for amount.

  196.     >>> count_change(7)
  197.     6
  198.     >>> count_change(10)
  199.     14
  200.     >>> count_change(20)
  201.     60
  202.     >>> count_change(100)
  203.     9828
  204.     """
  205.     "*** YOUR CODE HERE ***"
  206.     def get_highest_power(n):
  207.         i = 0
  208.         while pow(2, i) <= n:
  209.             i += 1
  210.         return i - 1
  211.    
  212.     highest_power = get_highest_power(amount)
  213.    
  214.     def count_partitions(num, highest_power):
  215.         if num < 0:
  216.             return 0
  217.         elif num == 0:
  218.             return 1
  219.         elif highest_power == 0:
  220.             return 1
  221.         else:
  222.             # Here we can count with two subgroups
  223.             # one with 2^highest_power and one without
  224.             with_highest = count_partitions(num - pow(2, highest_power), highest_power)
  225.             without_highest = count_partitions(num, highest_power - 1)
  226.             return with_highest + without_highest
  227.         
  228.     return count_partitions(amount, highest_power)
  229.    
  230.    
  231.    

  232. ###################
  233. # Extra Questions #
  234. ###################

  235. from operator import sub, mul

  236. def make_anonymous_factorial():
  237.     """Return the value of an expression that computes factorial.

  238.     >>> make_anonymous_factorial()(5)
  239.     120
  240.     >>> from construct_check import check
  241.     >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
  242.     True
  243.     """
  244.     return
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-7-31 15:57:33 | 只看该作者
全局:
  1. HW_SOURCE_FILE = 'hw04.py'

  2. ###############
  3. #  Questions  #
  4. ###############

  5. def intersection(st, ave):
  6.     """Represent an intersection using the Cantor pairing function."""
  7.     return (st+ave)*(st+ave+1)//2 + ave

  8. def street(inter):
  9.     return w(inter) - avenue(inter)

  10. def avenue(inter):
  11.     return inter - (w(inter) ** 2 + w(inter)) // 2

  12. w = lambda z: int(((8*z+1)**0.5-1)/2)

  13. def taxicab(a, b):
  14.     """Return the taxicab distance between two intersections.

  15.     >>> times_square = intersection(46, 7)
  16.     >>> ess_a_bagel = intersection(51, 3)
  17.     >>> taxicab(times_square, ess_a_bagel)
  18.     9
  19.     >>> taxicab(ess_a_bagel, times_square)
  20.     9
  21.     """
  22.     "*** YOUR CODE HERE ***"

  23.     return abs(street(a) - street(b)) + abs(avenue(a) - avenue(b))
  24.    
  25.    
  26.    

  27. def squares(s):
  28.     """Returns a new list containing square roots of the elements of the
  29.     original list that are perfect squares.

  30.     >>> seq = [8, 49, 8, 9, 2, 1, 100, 102]
  31.     >>> squares(seq)
  32.     [7, 3, 1, 10]
  33.     >>> seq = [500, 30]
  34.     >>> squares(seq)
  35.     []
  36.     """
  37.     "*** YOUR CODE HERE ***"
  38.     from math import sqrt
  39.     output = []
  40.     for i in s:
  41.         if sqrt(i) == round(sqrt(i)):
  42.             output.append(sqrt(i))
  43.     return output
  44.         
  45. #   official solution
  46. #   return [round(n**0.5) for n in s if round(n**0.5) ** 2 == n]

  47. def g(n):
  48.     """Return the value of G(n), computed recursively.

  49.     >>> g(1)
  50.     1
  51.     >>> g(2)
  52.     2
  53.     >>> g(3)
  54.     3
  55.     >>> g(4)
  56.     10
  57.     >>> g(5)
  58.     22
  59.     >>> from construct_check import check
  60.     >>> check(HW_SOURCE_FILE, 'g', ['While', 'For'])
  61.     True
  62.     """
  63.     "*** YOUR CODE HERE ***"
  64.     if n == 1:
  65.         return 1
  66.     elif n == 2:
  67.         return 2
  68.     elif n == 3:
  69.         return 3
  70.     else:
  71.         return g(n-1) + 2 * g(n-2) + 3 * g(n-3)
  72.    
  73.    

  74. def g_iter(n):
  75.     """Return the value of G(n), computed iteratively.

  76.     >>> g_iter(1)
  77.     1
  78.     >>> g_iter(2)
  79.     2
  80.     >>> g_iter(3)
  81.     3
  82.     >>> g_iter(4)
  83.     10
  84.     >>> g_iter(5)
  85.     22
  86.     >>> from construct_check import check
  87.     >>> check(HW_SOURCE_FILE, 'g_iter', ['Recursion'])
  88.     True
  89.     """
  90.     "*** YOUR CODE HERE ***"
  91.     # iteration method要找到更新的规律,用while来进行update。
  92.     if n <= 3:
  93.         return n
  94.     else:
  95.         num1, num2, num3 = 1, 2, 3
  96.         i = 3
  97.         while i < n:
  98.             num1, num2, num3 = num2, num3, 3 * num1 + 2 * num2 + num3
  99.             i += 1
  100.         return num3
  101.             
  102.    
  103.    

  104. def pingpong(n):
  105.     """Return the nth element of the ping-pong sequence.

  106.     >>> pingpong(7)
  107.     7
  108.     >>> pingpong(8)
  109.     6
  110.     >>> pingpong(15)
  111.     1
  112.     >>> pingpong(21)
  113.     -1
  114.     >>> pingpong(22)
  115.     0
  116.     >>> pingpong(30)
  117.     6
  118.     >>> pingpong(68)
  119.     2
  120.     >>> pingpong(69)
  121.     1
  122.     >>> pingpong(70)
  123.     0
  124.     >>> pingpong(71)
  125.     1
  126.     >>> pingpong(72)
  127.     0
  128.     >>> pingpong(100)
  129.     2
  130.     >>> from construct_check import check
  131.     >>> check(HW_SOURCE_FILE, 'pingpong', ['Assign', 'AugAssign'])
  132.     True
  133.     """
  134.     "*** YOUR CODE HERE ***"
  135.    
  136.     def make_switch(x):
  137.         if (has_seven(x)) or (x % 7 == 0):
  138.             return True
  139.         else:
  140.             return False
  141.    
  142.     def count(x, num, switch_indicator):
  143.         if x == n: # stopping critiria
  144.             return num
  145.         elif make_switch(x):
  146.             if switch_indicator % 2 == 0:
  147.                 return count(x + 1, num - 1, switch_indicator + 1)
  148.             else:
  149.                 return count(x + 1, num + 1, switch_indicator + 1)
  150.         else:
  151.             if switch_indicator % 2 == 0:
  152.                 return count(x + 1, num + 1, switch_indicator)
  153.             else:
  154.                 return count(x + 1, num - 1, switch_indicator)
  155.     return count(1, 1, 0)
  156.         

  157.    
  158.    
  159.    
  160. # Iteration method, but not okay in this question.
  161. #    i = 1
  162. #    output = 1
  163. #    multiplier = 1
  164. #    while i < n:
  165. #        if (has_seven(i)) or (i % 7 == 0):
  166. #            multiplier = multiplier * (-1)
  167. #        output = output + multiplier
  168. #        i += 1
  169. #            
  170. #    return output
  171.             
  172.    

  173. def has_seven(k):
  174.     """Returns True if at least one of the digits of k is a 7, False otherwise.

  175.     >>> has_seven(3)
  176.     False
  177.     >>> has_seven(7)
  178.     True
  179.     >>> has_seven(2734)
  180.     True
  181.     >>> has_seven(2634)
  182.     False
  183.     >>> has_seven(734)
  184.     True
  185.     >>> has_seven(7777)
  186.     True
  187.     """
  188.     if k % 10 == 7:
  189.         return True
  190.     elif k < 10:
  191.         return False
  192.     else:
  193.         return has_seven(k // 10)

  194. def count_change(amount):
  195.     """Return the number of ways to make change for amount.

  196.     >>> count_change(7)
  197.     6
  198.     >>> count_change(10)
  199.     14
  200.     >>> count_change(20)
  201.     60
  202.     >>> count_change(100)
  203.     9828
  204.     """
  205.     "*** YOUR CODE HERE ***"
  206.     def get_highest_power(n):
  207.         i = 0
  208.         while pow(2, i) <= n:
  209.             i += 1
  210.         return i - 1
  211.    
  212.     highest_power = get_highest_power(amount)
  213.    
  214.     def count_partitions(num, highest_power):
  215.         if num < 0:
  216.             return 0
  217.         elif num == 0:
  218.             return 1
  219.         elif highest_power == 0:
  220.             return 1
  221.         else:
  222.             # Here we can count with two subgroups
  223.             # one with 2^highest_power and one without
  224.             with_highest = count_partitions(num - pow(2, highest_power), highest_power)
  225.             without_highest = count_partitions(num, highest_power - 1)
  226.             return with_highest + without_highest
  227.         
  228.     return count_partitions(amount, highest_power)
  229.    
  230.    
  231.    

  232. ###################
  233. # Extra Questions #
  234. ###################

  235. from operator import sub, mul

  236. def make_anonymous_factorial():
  237.     """Return the value of an expression that computes factorial.

  238.     >>> make_anonymous_factorial()(5)
  239.     120
  240.     >>> from construct_check import check
  241.     >>> check(HW_SOURCE_FILE, 'make_anonymous_factorial', ['Assign', 'AugAssign', 'FunctionDef', 'Recursion'])
  242.     True
  243.     """
  244.     return
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-2 01:41:29 | 只看该作者
全局:
lab04
  1. """ Lab 04: Lists and Data Abstraction """

  2. # Q2
  3. def if_this_not_that(i_list, this):
  4.     """Define a function which takes a list of integers `i_list` and an integer
  5.     `this`. For each element in `i_list`, print the element if it is larger
  6.     than `this`; otherwise, print the word "that".

  7.     >>> original_list = [1, 2, 3, 4, 5]
  8.     >>> if_this_not_that(original_list, 3)
  9.     that
  10.     that
  11.     that
  12.     4
  13.     5
  14.     """
  15.     "*** YOUR CODE HERE ***"
  16.     for i in i_list:
  17.         if i > this:
  18.             print(i)
  19.         else:
  20.             print('that')
  21.             

  22. # City ADT
  23. def make_city(name, lat, lon):
  24.     """
  25.     >>> city = make_city('Berkeley', 0, 1)
  26.     >>> get_name(city)
  27.     'Berkeley'
  28.     >>> get_lat(city)
  29.     0
  30.     >>> get_lon(city)
  31.     1
  32.     """
  33.     return [name, lat, lon]

  34. def get_name(city):
  35.     """
  36.     >>> city = make_city('Berkeley', 0, 1)
  37.     >>> get_name(city)
  38.     'Berkeley'
  39.     """
  40.     return city[0]

  41. def get_lat(city):
  42.     """
  43.     >>> city = make_city('Berkeley', 0, 1)
  44.     >>> get_lat(city)
  45.     0
  46.     """
  47.     return city[1]

  48. def get_lon(city):
  49.     """
  50.     >>> city = make_city('Berkeley', 0, 1)
  51.     >>> get_lon(city)
  52.     1
  53.     """
  54.     return city[2]

  55. # Q4
  56. from math import sqrt
  57. def distance(city1, city2):
  58.     """
  59.     >>> city1 = make_city('city1', 0, 1)
  60.     >>> city2 = make_city('city2', 0, 2)
  61.     >>> distance(city1, city2)
  62.     1.0
  63.     >>> city3 = make_city('city3', 6.5, 12)
  64.     >>> city4 = make_city('city4', 2.5, 15)
  65.     >>> distance(city3, city4)
  66.     5.0
  67.     """
  68.     "*** YOUR CODE HERE ***"
  69.     return sqrt((get_lat(city1) - get_lat(city2))**2  +  (get_lon(city1) - get_lon(city2))**2)

  70. # Q5
  71. def closer_city(lat, lon, city1, city2):
  72.     """
  73.     Returns the name of either city1 or city2, whichever is closest to
  74.     coordinate (lat, lon).

  75.     >>> berkeley = make_city('Berkeley', 37.87, 112.26)
  76.     >>> stanford = make_city('Stanford', 34.05, 118.25)
  77.     >>> closer_city(38.33, 121.44, berkeley, stanford)
  78.     'Stanford'
  79.     >>> bucharest = make_city('Bucharest', 44.43, 26.10)
  80.     >>> vienna = make_city('Vienna', 48.20, 16.37)
  81.     >>> closer_city(41.29, 174.78, bucharest, vienna)
  82.     'Bucharest'
  83.     """
  84.     "*** YOUR CODE HERE ***"
  85.     city3 = make_city("new_city", lat, lon)
  86.     if distance(city3, city1) > distance(city3, city2):
  87.         return get_name(city2)
  88.     else:
  89.         return get_name(city1)

  90. # Q6
  91. # This is another implementation of the City ADT. Make sure
  92. # your code works for both the previous and the following versions
  93. # of the constructor and selectors!
  94. #
  95. make_city = lambda name, lat, lon: [lon, [lat], name]
  96. get_name = lambda city: city[2]
  97. get_lat = lambda city: city[1][0]
  98. get_lon = lambda city: city[0]



复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-3 07:53:54 | 只看该作者
全局:
Lab04 Extra

  1. """ Lab 04 Optional Questions """

  2. from lab04 import *

  3. # Q6
  4. def flatten(lst):
  5.     """Returns a flattened version of lst.

  6.     >>> flatten([1, 2, 3])     # normal list
  7.     [1, 2, 3]
  8.     >>> x = [1, [2, 3], 4]      # deep list
  9.     >>> flatten(x)
  10.     [1, 2, 3, 4]
  11.     >>> x = [[1, [1, 1]], 1, [1, 1]] # deep list
  12.     >>> flatten(x)
  13.     [1, 1, 1, 1, 1, 1]
  14.     """
  15.     "*** YOUR CODE HERE ***"
  16. ## My solution
  17.     new_lst = []
  18.     for item in lst:
  19.         if type(item) == list:
  20.             new_lst.extend(flatten(item))
  21.         else:
  22.             new_lst.append(item)
  23.     return new_lst

  24. ### Official solution
  25. ### The first element in the lst is either none or list or element.
  26. ### if none, return none; if list, flatten list; if element, 加上去。
  27.     if not lst:
  28.         return []
  29.     elif type(lst[0]) == list:
  30.         return flatten(lst[0]) + flatten(lst[1:])
  31.     else:
  32.         return [lst[0]] + flatten(lst[1:])
  33.                

  34. # Q7
  35. def merge(lst1, lst2):
  36.     """Merges two sorted lists.

  37.     >>> merge([1, 3, 5], [2, 4, 6])
  38.     [1, 2, 3, 4, 5, 6]
  39.     >>> merge([], [2, 4, 6])
  40.     [2, 4, 6]
  41.     >>> merge([1, 2, 3], [])
  42.     [1, 2, 3]
  43.     >>> merge([5, 7], [2, 4, 6])
  44.     [2, 4, 5, 6, 7]
  45.     """
  46.     "*** YOUR CODE HERE ***"
  47. #    output_lst = []
  48. #    i = 0
  49. #    j = 0
  50. #    if len(lst1) == 0:
  51. #        return lst2
  52. #    elif len(lst2) == 0:
  53. #        return lst1
  54. #    else:
  55. #        while i < len(lst1) and j < len(lst2):
  56. #            if lst1[i] < lst2[j]:
  57. #                output_lst.append(lst1[i])
  58. #                i += 1
  59. #            else:
  60. #                output_lst.append(lst2[j])
  61. #                j += 1
  62. #        while i < len(lst1):
  63. #            output_lst.append(lst1[i])
  64. #            i += 1
  65. #        while j < len(lst2):
  66. #            output_lst.append(lst2[j])
  67. #            j += 1
  68. #        return output_lst
  69.    
  70. ## Using for loop
  71. ## My solution, iterative solution
  72.     output_lst = []
  73.     i = 0
  74.     j = 0
  75.     if len(lst1) == 0:
  76.         return lst2
  77.     elif len(lst2) == 0:
  78.         return lst1
  79.     else:
  80.         for k in range(len(lst1) + len(lst2) - 1):
  81.             if lst1[i] < lst2[j]:
  82.                 output_lst.append(lst1[i])
  83.                 i += 1
  84.             else:
  85.                 output_lst.append(lst2[j])
  86.                 j += 1
  87.         if i < len(lst1):
  88.             output_lst.append(lst1[i])
  89.             i += 1
  90.         if j < len(lst2):
  91.             output_lst.append(lst2[j])
  92.             j += 1
  93.         return output_lst
  94.    
  95.    
  96. ## Official solution:
  97. ## Recursive solution: 先检查是否为None,若至少一个为none,则可以加起来。
  98.     if not lst1 or not lst2:
  99.         return lst1 + lst2
  100.     elif lst1[0] < lst2[0]:
  101.         return [lst1[0]] + merge(lst1[1:], lst2)
  102.     elif lst1[0] >= lst2[0]:
  103.         return [lst2[0]] + merge(lst1, lst2[1:])


  104. ######################
  105. ### Connect N Game ###
  106. ######################

  107. def create_row(size):
  108.     """Returns a single, empty row with the given size. Each empty spot is
  109.     represented by the string '-'.

  110.     >>> create_row(5)
  111.     ['-', '-', '-', '-', '-']
  112.     """
  113.     "*** YOUR CODE HERE ***"
  114.     return ['-' for i in range(size)]
  115.    


  116. def create_board(rows, columns):
  117.     """Returns a board with the given dimensions.

  118.     >>> create_board(3, 5)
  119.     [['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-']]
  120.     """
  121.     "*** YOUR CODE HERE ***"
  122.     return [create_row(columns) for row in range(rows)]
  123.    


  124. def replace_elem(lst, index, elem):
  125.     """Create and return a new list whose elements are the same as those in
  126.     LST except at index INDEX, which should contain element ELEM instead.

  127.     >>> old = [1, 2, 3, 4, 5, 6, 7]
  128.     >>> new = replace_elem(old, 2, 8)
  129.     >>> new
  130.     [1, 2, 8, 4, 5, 6, 7]
  131.     >>> new is old   # check that replace_elem outputs a new list
  132.     False
  133.     """
  134.     assert index >= 0 and index < len(lst), 'Index is out of bounds'
  135.     "*** YOUR CODE HERE ***"
  136.     return lst[:index] + [elem] + lst[index + 1:]


  137. def get_piece(board, row, column):
  138.     """Returns the piece at location (row, column) in the board.

  139.     >>> rows, columns = 2, 2
  140.     >>> board = create_board(rows, columns)
  141.     >>> board = put_piece(board, rows, 0, 'X')[1] # Puts piece "X" in column 0 of board and updates board
  142.     >>> board = put_piece(board, rows, 0, 'O')[1] # Puts piece "O" in column 0 of board and updates board
  143.     >>> get_piece(board, 1, 0)
  144.     'X'
  145.     >>> get_piece(board, 1, 1)
  146.     '-'
  147.     """
  148.     "*** YOUR CODE HERE ***"
  149.     return board[row][column]


  150. def put_piece(board, max_rows, column, player):
  151.     """Puts PLAYER's piece in the bottommost empty spot in the given column of
  152.     the board. Returns a tuple of two elements:

  153.         1. The index of the row the piece ends up in, or -1 if the column
  154.            is full.
  155.         2. The new board

  156.     >>> rows, columns = 2, 2
  157.     >>> board = create_board(rows, columns)
  158.     >>> row, new_board = put_piece(board, rows, 0, 'X')
  159.     >>> row
  160.     1
  161.     >>> row, new_board = put_piece(new_board, rows, 0, 'O')
  162.     >>> row
  163.     0
  164.     >>> row, new_board = put_piece(new_board, rows, 0, 'X')
  165.     >>> row
  166.     -1
  167.     """
  168.     "*** YOUR CODE HERE ***"
  169.     for row in range(max_rows - 1, -1, -1):
  170.         if get_piece(board, row, column) == '-':
  171.             new_row = replace_elem(board[row], column, player)
  172.             new_board = replace_elem(board, row, new_row)
  173.             return row, new_board
  174.     return -1, board
  175.             
  176.    


  177. def make_move(board, max_rows, max_cols, col, player):
  178.     """Put player's piece in column COL of the board, if it is a valid move.
  179.     Return a tuple of two values:

  180.         1. If the move is valid, make_move returns the index of the row the
  181.            piece is placed in. Otherwise, it returns -1.
  182.         2. The updated board

  183.     >>> rows, columns = 2, 2
  184.     >>> board = create_board(rows, columns)
  185.     >>> row, board = make_move(board, rows, columns, 0, 'X')
  186.     >>> row
  187.     1
  188.     >>> get_piece(board, 1, 0)
  189.     'X'
  190.     >>> row, board = make_move(board, rows, columns, 0, 'O')
  191.     >>> row
  192.     0
  193.     >>> row, board = make_move(board, rows, columns, 0, 'X')
  194.     >>> row
  195.     -1
  196.     >>> row, board = make_move(board, rows, columns, -4, '0')
  197.     >>> row
  198.     -1
  199.     """
  200.     "*** YOUR CODE HERE ***"
  201.     if col >= 0 and col <= max_cols - 1:
  202.         row, new_board = put_piece(board, max_rows, col, player)
  203.         return row, new_board
  204.     else:
  205.         return -1, board
  206.    

  207. def print_board(board, max_rows, max_cols):
  208.     """Prints the board. Row 0 is at the top, and column 0 at the far left.

  209.     >>> rows, columns = 2, 2
  210.     >>> board = create_board(rows, columns)
  211.     >>> print_board(board, rows, columns)
  212.     - -
  213.     - -
  214.     >>> new_board = make_move(board, rows, columns, 0, 'X')[1]
  215.     >>> print_board(new_board, rows, columns)
  216.     - -
  217.     X -
  218.     """
  219.     "*** YOUR CODE HERE ***"
  220.     for row in range(max_rows):
  221.         output = ''
  222.         for column in range(max_cols):
  223.             output = output + get_piece(board, row, column) + ' '
  224.         print(output.strip())
  225.             
  226.    

  227. def check_win_row(board, max_rows, max_cols, num_connect, row, player):
  228.     """ Returns True if the given player has a horizontal win
  229.     in the given row, and otherwise False.

  230.     >>> rows, columns, num_connect = 4, 4, 2
  231.     >>> board = create_board(rows, columns)
  232.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  233.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  234.     >>> check_win_row(board, rows, columns, num_connect, 3, 'O')
  235.     False
  236.     >>> board = make_move(board, rows, columns, 2, 'X')[1]
  237.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  238.     >>> check_win_row(board, rows, columns, num_connect, 3, 'X')
  239.     False
  240.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  241.     >>> check_win_row(board, rows, columns, num_connect, 3, 'X')
  242.     True
  243.     >>> check_win_row(board, rows, columns, 4, 3, 'X')    # A win depends on the value of num_connect
  244.     False
  245.     >>> check_win_row(board, rows, columns, num_connect, 3, 'O')   # We only detect wins for the given player
  246.     False
  247.     """
  248.     "*** YOUR CODE HERE ***"
  249.     ## for each row, check the adject number of player
  250.     adjacent = 0
  251.     for col in range(max_cols):
  252.         piece = get_piece(board, row, col)
  253.         if piece != player:
  254.             adjacent = 0
  255.         else:
  256.             adjacent += 1
  257.         if adjacent >= num_connect:
  258.             return True
  259.     return False
  260.         
  261.    
  262.    

  263. def check_win_column(board, max_rows, max_cols, num_connect, col, player):
  264.     """ Returns True if the given player has a vertical win in the given column,
  265.     and otherwise False.

  266.     >>> rows, columns, num_connect = 5, 5, 2
  267.     >>> board = create_board(rows, columns)
  268.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  269.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  270.     >>> check_win_column(board, rows, columns, num_connect, 0, 'X')
  271.     False
  272.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  273.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  274.     >>> check_win_column(board, rows, columns, num_connect, 1, 'O')
  275.     False
  276.     >>> board = make_move(board, rows, columns, 2, 'X')[1]
  277.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  278.     >>> check_win_column(board, rows, columns, num_connect, 1, 'O')
  279.     True
  280.     >>> check_win_column(board, rows, columns, 4, 1, 'O')
  281.     False
  282.     >>> check_win_column(board, rows, columns, num_connect, 1, 'X')
  283.     False
  284.     """
  285.     "*** YOUR CODE HERE ***"
  286.     adjacent = 0
  287.     for row in range(max_rows):
  288.         piece = get_piece(board, row, col)
  289.         if piece != player:
  290.             adjacent = 0
  291.         else:
  292.             adjacent += 1
  293.         if adjacent >= num_connect:
  294.             return True
  295.     return False
  296.    

  297. def check_win(board, max_rows, max_cols, num_connect, row, col, player):
  298.     """Returns True if the given player has any kind of win after placing a
  299.     piece at (row, col), and False otherwise.

  300.     >>> rows, columns, num_connect = 2, 2, 2
  301.     >>> board = create_board(rows, columns)
  302.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  303.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  304.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  305.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'O')
  306.     False
  307.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  308.     True

  309.     >>> board = create_board(rows, columns)
  310.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  311.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  312.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  313.     >>> check_win(board, rows, columns, num_connect, 1, 0, 'X')
  314.     True
  315.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  316.     False

  317.     >>> board = create_board(rows, columns)
  318.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  319.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  320.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  321.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  322.     False
  323.     >>> check_win(board, rows, columns, num_connect, 1, 0, 'X')
  324.     True
  325.     """
  326.     diagonal_win = check_win_diagonal(board, max_rows, max_cols, num_connect,
  327.                                       row, col, player)
  328.     "*** YOUR CODE HERE ***"
  329.     row_win = check_win_row(board, max_rows, max_cols, num_connect, row,
  330.                              player)
  331.     column_win = check_win_column(board, max_rows, max_cols, num_connect,
  332.                                    col, player)
  333.     if diagonal_win or row_win or column_win:
  334.         return True
  335.     else:
  336.         return False
  337.    
  338.    

  339. ###############################################################
  340. ### Functions for reference when solving the other problems ###
  341. ###############################################################

  342. def check_win_diagonal(board, max_rows, max_cols, num_connect, row, col, player):
  343.     """ Returns True if the given player has a diagonal win passing the spot
  344.     (row, column), and False otherwise.
  345.     """
  346.     # Find top left of diagonal passing through the newly placed piece.
  347.     adjacent = 0
  348.     row_top_left, col_top_left = row, col
  349.     while row_top_left > 0 and col_top_left > 0:
  350.         row_top_left -= 1
  351.         col_top_left -= 1

  352.     # Loop through top left to bottom right diagonal and check for win.
  353.     while row_top_left < max_rows and col_top_left < max_cols:
  354.         piece = get_piece(board, row_top_left, col_top_left)
  355.         if piece == player:
  356.             adjacent += 1
  357.         else:
  358.             adjacent = 0
  359.         if adjacent >= num_connect:
  360.             return True
  361.         row_top_left += 1
  362.         col_top_left += 1

  363.     # Find top right of diagonal passing through the newly placed piece.
  364.     adjacent = 0
  365.     row_top_right, col_top_right = row, col
  366.     while row_top_right > 0 and col_top_right < max_cols - 1:
  367.         row_top_right -= 1
  368.         col_top_right += 1

  369.     # Loop through top right to bottom left diagonal and check for win.
  370.     while row_top_right < max_rows and col_top_right >= 0:
  371.         piece = get_piece(board, row_top_right, col_top_right)
  372.         if piece == player:
  373.             adjacent += 1
  374.         else:
  375.             adjacent = 0
  376.         if adjacent >= num_connect:
  377.             return True
  378.         row_top_right += 1
  379.         col_top_right -= 1

  380.     return False

  381. #####################################################################################
  382. ### You do not need to read or understand the following code for this assignment. ###
  383. #####################################################################################

  384. import sys

  385. def other(player):
  386.     """ Returns the given player's opponent.
  387.     """
  388.     if player == 'X':
  389.         return 'O'
  390.     return 'X'

  391. def play(board, max_rows, max_cols, num_connect):
  392.     max_turns = max_rows * max_cols
  393.     playing = True
  394.     print("Player 'X' starts")
  395.     who = 'X'
  396.     turns = 0

  397.     while True:
  398.         turns += 1
  399.         if turns > max_turns:
  400.             print("No more moves. It's a tie!")
  401.             sys.exit()

  402.         while True:
  403.             try:
  404.                 col_index = int(input('Which column, player {}? '.format(who)))
  405.             except ValueError as e:
  406.                 print('Invalid input. Please try again.')
  407.                 continue

  408.             row_index, board = make_move(board, max_rows, max_cols, col_index, who)

  409.             if row_index != -1:
  410.                 break

  411.             print("Oops, you can't put a piece there")

  412.         print_board(board, max_rows, max_cols)

  413.         if check_win(board, max_rows, max_cols, num_connect, row_index, col_index, who):
  414.             print("Player {} wins!".format(who))
  415.             sys.exit()

  416.         who = other(who)

  417. def start_game():
  418.     # Get all parameters for the game from user.
  419.     while True:
  420.         # Get num_connect from user.
  421.         while True:
  422.             try:
  423.                 num_connect = int(input('How many to connect (e.g. 4 for Connect 4)? '))
  424.             except ValueError as e:
  425.                 print('Invalid input. Please try again.')
  426.                 continue
  427.             break

  428.         # Get number of rows for board from user.
  429.         while True:
  430.             try:
  431.                  max_rows = int(input('How many rows? '))
  432.             except ValueError as e:
  433.                 print('Invalid input. Please try again.')
  434.                 continue
  435.             break

  436.         # Get number of columns for board from user.
  437.         while True:
  438.             try:
  439.                 max_cols = int(input('How many columns? '))
  440.             except ValueError as e:
  441.                 print('Invalid input. Please try again.')
  442.                 continue
  443.             break

  444.         if max_rows >= num_connect or max_cols >= num_connect:
  445.             break
  446.         print("Invalid dimensions for connect {0}. Please try again.".format(num_connect))

  447.     board = create_board(max_rows, max_cols)
  448.     play(board, max_rows, max_cols, num_connect)
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-3 12:11:15 | 只看该作者
全局:
TREE RECURSION AND DATA ABSTRACTION
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 30 16:19:14 2019

  4. @author:
  5. """

  6. def is_sorted(n):
  7.     all_but_last, last = n // 10, n % 10
  8.     if all_but_last == 0:
  9.         return True
  10.     elif all_but_last % 10 > last:
  11.         return is_sorted(all_but_last)
  12.     else:
  13.         return False
  14.    
  15.     ### 第一次跳一个或者两个来分类,然后考虑base case
  16.     ###
  17. ## My solution
  18. def mario_number(level):
  19.     if len(level) == 0 or level[0] == '0':
  20.         return 0
  21.     elif len(level) <= 2:
  22.         return 1
  23.     else:
  24.         return mario_number(level[1:]) + mario_number(level[2:])

  25. ## Official solution
  26. def mario_number(level):
  27.     if level == 1:
  28.         return 1
  29.     elif level % 10 == 0:
  30.         return 0
  31.     else:
  32.         return mario_number(level // 10) + mario_number(level // 10 // 10)


  33. ## My solution, math.
  34. def make_change(n):
  35.     if n < 1:
  36.         return 0
  37.     elif n < 3:
  38.         return n
  39.     else:
  40.         return min(n // 4 + n % 4 // 3 + n % 4 % 3, n // 3 + n % 3)
  41.    
  42.    
  43. ## Other solution, recursive
  44.     if n == 0:
  45.         return 0
  46.     elif n in [1, 3, 4]:
  47.         return 1
  48.     elif n == 2:
  49.         return 2
  50.     else:
  51.         return min([make_change(n - i) + 1 for i in [1, 3, 4]])




  52. def elephant(name, age, can_fly):
  53.     return [name, age, can_fly]

  54. def elephant_name(e):
  55.     return e[0]

  56. def elephant_age(e):
  57.     return e[1]

  58. def elephant_can_fly(e):
  59.     return e[2]
  60.    

  61. def elephant_roster(elephants):
  62.     return [elephant_name(elephant) for elephant in elephants]
  63. ### Cannot break the abstraction barrier
  64.    

  65. def elephant(name, age, can_fly):
  66.     return [[name, age], can_fly]

  67. def elephant_roster(elephants):
  68.     return [elephant_name(elephant) for elephant in elephants]


  69. def elephant_2(name, age, can_fly):
  70.     def select(command):
  71.         if command == 'name':
  72.             return name
  73.         elif command == 'age':
  74.             return age
  75.         elif command == 'can_fly':
  76.             return can_fly
  77.     return select
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-5 04:56:29 | 只看该作者
全局:
Project Yelp Maps finished.
这次的project比较简单,而且有很多helper code。不知道把这种project放进简历里面是不是太水了。。。
  1. """A Yelp-powered Restaurant Recommendation Program"""

  2. from abstractions import *
  3. from data import ALL_RESTAURANTS, CATEGORIES, USER_FILES, load_user_file
  4. from ucb import main, trace, interact
  5. from utils import distance, mean, zip, enumerate, sample
  6. from visualize import draw_map

  7. ##################################
  8. # Phase 2: Unsupervised Learning #
  9. ##################################


  10. def find_closest(location, centroids):
  11.     """Return the centroid in centroids that is closest to location.
  12.     If multiple centroids are equally close, return the first one.

  13.     >>> find_closest([3.0, 4.0], [[0.0, 0.0], [2.0, 3.0], [4.0, 3.0], [5.0, 5.0]])
  14.     [2.0, 3.0]
  15.     """
  16.     # BEGIN Question 3
  17.     "*** YOUR CODE HERE ***"
  18.     return min(centroids, key = lambda centroid: distance(centroid, location))

  19.    
  20.     # END Question 3


  21. def group_by_first(pairs):
  22.     """Return a list of pairs that relates each unique key in the [key, value]
  23.     pairs to a list of all values that appear paired with that key.

  24.     Arguments:
  25.     pairs -- a sequence of pairs

  26.     >>> example = [ [1, 2], [3, 2], [2, 4], [1, 3], [3, 1], [1, 2] ]
  27.     >>> group_by_first(example)
  28.     [[2, 3, 2], [2, 1], [4]]
  29.     """
  30.     keys = []
  31.     for key, _ in pairs:
  32.         if key not in keys:
  33.             keys.append(key)
  34.     return [[y for x, y in pairs if x == key] for key in keys]


  35. def group_by_centroid(restaurants, centroids):
  36.     """Return a list of clusters, where each cluster contains all restaurants
  37.     nearest to a corresponding centroid in centroids. Each item in
  38.     restaurants should appear once in the result, along with the other
  39.     restaurants closest to the same centroid.
  40.     """
  41.     # BEGIN Question 4
  42.     "*** YOUR CODE HERE ***"
  43.     pairs = []
  44.     for r in restaurants:
  45.         closest_centroid = find_closest(restaurant_location(r), centroids)
  46.         pairs.append([closest_centroid, r])
  47.    
  48.     return group_by_first(pairs)
  49.    
  50.     # END Question 4


  51. def find_centroid(cluster):
  52.     """Return the centroid of the locations of the restaurants in cluster."""
  53.     # BEGIN Question 5
  54.     "*** YOUR CODE HERE ***"
  55.     latitude = []
  56.     longitude = []
  57.     for r in cluster:
  58.         latitude.append(restaurant_location(r)[0])
  59.         longitude.append(restaurant_location(r)[1])
  60.         
  61.     return [mean(latitude), mean(longitude)]
  62.     # END Question 5


  63. def k_means(restaurants, k, max_updates=100):
  64.     """Use k-means to group restaurants by location into k clusters."""
  65.     assert len(restaurants) >= k, 'Not enough restaurants to cluster'
  66.     old_centroids, n = [], 0
  67.     # Select initial centroids randomly by choosing k different restaurants
  68.     centroids = [restaurant_location(r) for r in sample(restaurants, k)]

  69.     while old_centroids != centroids and n < max_updates:
  70.         old_centroids = centroids
  71.         # BEGIN Question 6
  72.         "*** YOUR CODE HERE ***"
  73.         clusters = group_by_centroid(restaurants, old_centroids)
  74.         centroids = []
  75.         for cluster in clusters:
  76.             centroids += [find_centroid(cluster)]
  77.         
  78.         # END Question 6
  79.         n += 1
  80.     return centroids


  81. ################################
  82. # Phase 3: Supervised Learning #
  83. ################################


  84. def find_predictor(user, restaurants, feature_fn):
  85.     """Return a rating predictor (a function from restaurants to ratings),
  86.     for a user by performing least-squares linear regression using feature_fn
  87.     on the items in restaurants. Also, return the R^2 value of this model.

  88.     Arguments:
  89.     user -- A user
  90.     restaurants -- A sequence of restaurants
  91.     feature_fn -- A function that takes a restaurant and returns a number
  92.     """
  93.     reviews_by_user = {review_restaurant_name(review): review_rating(review)
  94.                        for review in user_reviews(user).values()}

  95.     xs = [feature_fn(r) for r in restaurants]
  96.     ys = [reviews_by_user[restaurant_name(r)] for r in restaurants]

  97.     # BEGIN Question 7
  98.     S_xy = sum((x - mean(xs)) * (y - mean(ys)) for x, y in zip(xs, ys))
  99.     S_xx= sum((x - mean(xs))**2 for x in xs)
  100.     S_yy = sum((y - mean(ys))**2 for y in ys)
  101.     b, a, r_squared = S_xy / S_xx, mean(ys) - S_xy / S_xx * mean(xs), S_xy**2 / (S_xx * S_yy)  # REPLACE THIS LINE WITH YOUR SOLUTION
  102.     # END Question 7

  103.     def predictor(restaurant):
  104.         return b * feature_fn(restaurant) + a

  105.     return predictor, r_squared


  106. def best_predictor(user, restaurants, feature_fns):
  107.     """Find the feature within feature_fns that gives the highest R^2 value
  108.     for predicting ratings by the user; return a predictor using that feature.

  109.     Arguments:
  110.     user -- A user
  111.     restaurants -- A list of restaurants
  112.     feature_fns -- A sequence of functions that each takes a restaurant
  113.     """
  114.     reviewed = user_reviewed_restaurants(user, restaurants)
  115.     # BEGIN Question 8
  116.     "*** YOUR CODE HERE ***"
  117.     pairs = []
  118.     for feature_fn in feature_fns:
  119.         pairs += [find_predictor(user, reviewed, feature_fn)]
  120.     return max(pairs, key = lambda x: x[1])[0]
  121.     # END Question 8
  122.    

  123. def rate_all(user, restaurants, feature_fns):
  124.     """Return the predicted ratings of restaurants by user using the best
  125.     predictor based on a function from feature_fns.

  126.     Arguments:
  127.     user -- A user
  128.     restaurants -- A list of restaurants
  129.     feature_fns -- A sequence of feature functions
  130.     """
  131.     predictor = best_predictor(user, ALL_RESTAURANTS, feature_fns)
  132.     reviewed = user_reviewed_restaurants(user, restaurants)
  133.     # BEGIN Question 9
  134.     "*** YOUR CODE HERE ***"
  135.     all_restaurant = {}
  136.     for r in restaurants:
  137.         name = restaurant_name(r)
  138.         if r in reviewed:
  139.             all_restaurant[name] = user_rating(user, name)
  140.         else:
  141.             all_restaurant[name] = predictor(r)
  142.             
  143.     return all_restaurant
  144.    
  145.     # END Question 9


  146. def search(query, restaurants):
  147.     """Return each restaurant in restaurants that has query as a category.

  148.     Arguments:
  149.     query -- A string
  150.     restaurants -- A sequence of restaurants
  151.     """
  152.     # BEGIN Question 10
  153.     "*** YOUR CODE HERE ***"
  154.     all_restaurant = []
  155.     for r in restaurants:
  156.         if query in restaurant_categories(r):
  157.             all_restaurant.append(r)
  158.         
  159.     return all_restaurant
  160.    
  161.     # END Question 10


  162. def feature_set():
  163.     """Return a sequence of feature functions."""
  164.     return [lambda r: mean(restaurant_ratings(r)),
  165.             restaurant_price,
  166.             lambda r: len(restaurant_ratings(r)),
  167.             lambda r: restaurant_location(r)[0],
  168.             lambda r: restaurant_location(r)[1]]


  169. @main
  170. def main(*args):
  171.     import argparse
  172.     parser = argparse.ArgumentParser(
  173.         description='Run Recommendations',
  174.         formatter_class=argparse.RawTextHelpFormatter
  175.     )
  176.     parser.add_argument('-u', '--user', type=str, choices=USER_FILES,
  177.                         default='test_user',
  178.                         metavar='USER',
  179.                         help='user file, e.g.\n' +
  180.                         '{{{}}}'.format(','.join(sample(USER_FILES, 3))))
  181.     parser.add_argument('-k', '--k', type=int, help='for k-means')
  182.     parser.add_argument('-q', '--query', choices=CATEGORIES,
  183.                         metavar='QUERY',
  184.                         help='search for restaurants by category e.g.\n'
  185.                         '{{{}}}'.format(','.join(sample(CATEGORIES, 3))))
  186.     parser.add_argument('-p', '--predict', action='store_true',
  187.                         help='predict ratings for all restaurants')
  188.     parser.add_argument('-r', '--restaurants', action='store_true',
  189.                         help='outputs a list of restaurant names')
  190.     args = parser.parse_args()

  191.     # Output a list of restaurant names
  192.     if args.restaurants:
  193.         print('Restaurant names:')
  194.         for restaurant in sorted(ALL_RESTAURANTS, key=restaurant_name):
  195.             print(repr(restaurant_name(restaurant)))
  196.         exit(0)

  197.     # Select restaurants using a category query
  198.     if args.query:
  199.         restaurants = search(args.query, ALL_RESTAURANTS)
  200.     else:
  201.         restaurants = ALL_RESTAURANTS

  202.     # Load a user
  203.     assert args.user, 'A --user is required to draw a map'
  204.     user = load_user_file('{}.dat'.format(args.user))

  205.     # Collect ratings
  206.     if args.predict:
  207.         ratings = rate_all(user, restaurants, feature_set())
  208.     else:
  209.         restaurants = user_reviewed_restaurants(user, restaurants)
  210.         names = [restaurant_name(r) for r in restaurants]
  211.         ratings = {name: user_rating(user, name) for name in names}

  212.     # Draw the visualization
  213.     if args.k:
  214.         centroids = k_means(restaurants, min(args.k, len(restaurants)))
  215.     else:
  216.         centroids = [restaurant_location(r) for r in restaurants]
  217.     draw_map(centroids, restaurants, ratings)
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-5 14:44:09 | 只看该作者
全局:
今天上完了第五周课程,做完了discussion 3
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Aug  4 17:46:44 2019
  4. topic: Trees & Sequences
  5. @author: jjjjjppp
  6. """
  7. a = [3, 1, 4, 2, 5, 3]
  8. a[1::2]
  9. a[:]
  10. a[4:2]
  11. a[1:-2]
  12. a[::-1]
  13. a[3::-1]
  14. [i + 1 for i in [1, 2, 3, 4, 5] if i % 2 == 0]

  15. [i * i - i for i in [5, -1, 3, -1, 3] if i > 2]
  16. [[y * 2 for y in [x, x + 1]] for x in [1, 2, 3, 4]]


  17. # Constructor
  18. def tree(label, branches = []):
  19.     for branch in branches:
  20.         assert is_tree(branch)
  21.     return [label] + list(branches)

  22. def is_tree(tree):
  23.     if type(tree) != list or len(tree) < 1:
  24.         return False
  25.     for branch in branches(tree):
  26.         if not is_tree(branch):
  27.             return False
  28.     return True
  29.    
  30. def label(tree):
  31.     return tree[0]

  32. def branches(tree):
  33.     return tree[1:]

  34. def is_leaf(tree):
  35.     return not branches(tree)

  36. t = tree(1,
  37.          [tree(3,
  38.                [tree(4),
  39.                 tree(5),
  40.                 tree(6)]),
  41.           tree(2)])

  42.    
  43. ## Questions 3.1
  44. def tree_max(t):
  45.     if is_leaf(t):
  46.         return label(t)
  47.     else:
  48.         return max([label(t)] + [tree_max(branch) for branch in branches(t)])
  49.    
  50. tree_max(t)

  51. ## 3.2
  52. def height(t):
  53.     if is_leaf(t):
  54.         return 0
  55.     else:
  56.         return 1 + max([height(branch) for branch in branches(t)])

  57. height(t)

  58. ## 3.3
  59. ## return a new tree, need to use the constructor
  60. def square_tree(t):
  61.     sq_branches = [square_tree(branch) for branch in branches(t)]
  62.     return tree(label(t) ** 2, sq_branches)
  63.    

  64. square_tree(t)


  65. ## 3.4
  66. def find_path(tree, x):
  67.     if x == label(tree):
  68.         return [x]
  69.     for b in branches(tree):
  70.         path = find_path(b, x)
  71.         if path:
  72.             return [label(tree)] + path
  73.    
  74. find_path(t, 6)
  75. find_path(t, 10)

  76. ## 3.5
  77. ## return a tree, need to use constructor
  78. def prune(t, k):
  79.     if k == 0:
  80.         return tree(label(t), [])
  81.     if k >= height(t):
  82.         return t
  83.     else:
  84.         return tree(label(t), [prune(b, k - 1) for b in branches(t)])

  85. prune(t, 5)   
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-5 15:32:53 | 只看该作者
全局:
CSM02

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sun Aug  4 23:54:09 2019
  4. CSM 02
  5. @author: jpjpjp
  6. """
  7. a = [1, 2, 3]
  8. a

  9. a[2]
  10. b = a
  11. a = a + [4, 5]
  12. b

  13. a

  14. c = a
  15. a = [4, 5]
  16. a

  17. c

  18. d = c[0:2]
  19. c[0] = 9
  20. d

  21. def reverse(lst):
  22.     if len(lst) <= 1:
  23.         return lst
  24.     return reverse(lst[1:]) + [lst[0]]
  25. lst = [1, [2, 3], 4]
  26. rev = reverse(lst)
  27. rev

  28. # 3
  29. def is_prime(n):
  30.     assert type(n) == int
  31.     if n <= 2:
  32.         return True
  33.     else:
  34.         k = 2
  35.         while k < (n // 2):
  36.             if n % k == 0:
  37.                 return False
  38.             k += 1
  39.         return True
  40.             

  41. def all_primes(nums):
  42.     return [num for num in nums if is_prime(num)]

  43. # 4
  44. def list_of_lists(lst):
  45.     if not lst:
  46.         return []
  47.     else:
  48.         full_lst = []
  49.         for elem in lst:
  50.             elems = [i for i in range(elem)]
  51.             full_lst.append(elems)
  52.         return full_lst
  53.             
  54. ## Trees
  55. def tree(label, branches = []):
  56.     return [label] + [branches]

  57. def label(tree):
  58.     return tree[0]

  59. def branches(tree):
  60.     return tree[1:]

  61. b = tree(4,
  62.      [tree(5, []),
  63.       tree(2,
  64.            [tree(2, []),
  65.             tree(1, [])]),
  66.     tree(1, []),
  67.     tree(8,
  68.          [tree(4, [])])])

  69. t = tree(9,
  70.          [tree(2, []),
  71.           tree(4,
  72.                [tree(1, [])]),
  73.                tree(4,
  74.                     [tree(7, []),
  75.                      tree(3, [])])])         
  76.    
  77.    
  78.    
  79. label(t)
  80. branches(t)[2]
  81. branches(branches(t)[2])[0]

  82. label(branches(t)[0])   

  83. def sum_of_nodes(t):
  84.     return label(t) + sum([sum_of_nodes(b) for b in branches(t)])
  85.    
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-6 06:16:20 | 只看该作者
全局:
趁着午休时间把lab05做了做,发现tree structure的题目都很有规律,做起来感觉蛮舒服。
  1. """ Lab 05: Mutable Sequences and Trees """
  2. # Q2
  3. def map(fn, seq):
  4.     """Applies fn onto each element in seq and returns a list.

  5.     >>> map(lambda x: x*x, [1, 2, 3])
  6.     [1, 4, 9]
  7.     """
  8.     "*** YOUR CODE HERE ***"
  9.     return [fn(elem) for elem in seq]

  10. def filter(pred, seq):
  11.     """Keeps elements in seq only if they satisfy pred.

  12.     >>> filter(lambda x: x % 2 == 0, [1, 2, 3, 4])
  13.     [2, 4]
  14.     """
  15.     "*** YOUR CODE HERE ***"
  16.     return [elem for elem in seq if pred(elem)]

  17. def reduce(combiner, seq):
  18.     """Combines elements in seq using combiner.

  19.     >>> reduce(lambda x, y: x + y, [1, 2, 3, 4])
  20.     10
  21.     >>> reduce(lambda x, y: x * y, [1, 2, 3, 4])
  22.     24
  23.     >>> reduce(lambda x, y: x * y, [4])
  24.     4
  25.     """
  26.     "*** YOUR CODE HERE ***"
  27.     if len(seq) == 1:
  28.         return seq[0]
  29.     else:
  30.         return combiner(seq[0], reduce(combiner, seq[1:]))
  31.    

  32. # Q3
  33. def acorn_finder(t):
  34.     """Returns True if t contains a node with the value 'acorn' and
  35.     False otherwise.

  36.     >>> scrat = tree('acorn')
  37.     >>> acorn_finder(scrat)
  38.     True
  39.     >>> sproul = tree('roots', [tree('branch1', [tree('leaf'), tree('acorn')]), tree('branch2')])
  40.     >>> acorn_finder(sproul)
  41.     True
  42.     >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
  43.     >>> acorn_finder(numbers)
  44.     False
  45.     """
  46.     "*** YOUR CODE HERE ***"
  47.     ### My solution
  48. #    if label(t) == 'acorn':
  49. #        return True
  50. #    elif label(t) != 'acorn' and is_leaf(t):
  51. #        return False
  52. #    else:
  53. #        if sum([acorn_finder(b) for b in branches(t)]) == 1:
  54. #            return True
  55. #        else:
  56. #            return False
  57.     ### Official solution
  58.     if label(t) == 'acorn':
  59.         return True
  60.     else:
  61.         for branch in branches(t):
  62.             if acorn_finder(branch) == True:
  63.                 return True
  64.     return False
  65.    
  66.    
  67.    
  68. # Q4
  69. def replace_leaf(t, old, new):
  70.     """Returns a new tree where every leaf value equal to old has
  71.     been replaced with new.

  72.     >>> yggdrasil = tree('odin',
  73.     ...                  [tree('balder',
  74.     ...                        [tree('thor'),
  75.     ...                         tree('loki')]),
  76.     ...                   tree('frigg',
  77.     ...                        [tree('thor')]),
  78.     ...                   tree('thor',
  79.     ...                        [tree('sif'),
  80.     ...                         tree('thor')]),
  81.     ...                   tree('thor')])
  82.     >>> laerad = copy_tree(yggdrasil) # copy yggdrasil for testing purposes
  83.     >>> print_tree(replace_leaf(yggdrasil, 'thor', 'freya'))
  84.     odin
  85.       balder
  86.         freya
  87.         loki
  88.       frigg
  89.         freya
  90.       thor
  91.         sif
  92.         freya
  93.       freya
  94.     >>> laerad == yggdrasil # Make sure original tree is unmodified
  95.     True
  96.     """
  97.     "*** YOUR CODE HERE ***"
  98.     if is_leaf(t):
  99.         if label(t) == old:
  100.             return tree(new)
  101.         else:
  102.             return t
  103.     else:
  104.         new_branches = [replace_leaf(b, old, new) for b in branches(t)]
  105.         return tree(label(t), new_branches)

  106.    
  107.    

  108. # Tree ADT
  109. def tree(label, branches=[]):
  110.     """Construct a tree with the given label value and a list of branches."""
  111.     for branch in branches:
  112.         assert is_tree(branch), 'branches must be trees'
  113.     return [label] + list(branches)

  114. def label(tree):
  115.     """Return the label value of a tree."""
  116.     return tree[0]

  117. def branches(tree):
  118.     """Return the list of branches of the given tree."""
  119.     return tree[1:]

  120. def is_tree(tree):
  121.     """Returns True if the given tree is a tree, and False otherwise."""
  122.     if type(tree) != list or len(tree) < 1:
  123.         return False
  124.     for branch in branches(tree):
  125.         if not is_tree(branch):
  126.             return False
  127.     return True

  128. def is_leaf(tree):
  129.     """Returns True if the given tree's list of branches is empty, and False
  130.     otherwise.
  131.     """
  132.     return not branches(tree)

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

  136.     >>> print_tree(tree(1))
  137.     1
  138.     >>> print_tree(tree(1, [tree(2)]))
  139.     1
  140.       2
  141.     >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
  142.     >>> print_tree(numbers)
  143.     1
  144.       2
  145.       3
  146.         4
  147.         5
  148.       6
  149.         7
  150.     """
  151.     print('  ' * indent + str(label(t)))
  152.     for b in branches(t):
  153.         print_tree(b, indent + 1)

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

  156.     >>> t = tree(5)
  157.     >>> copy = copy_tree(t)
  158.     >>> t = tree(6)
  159.     >>> print_tree(copy)
  160.     5
  161.     """
  162.     return tree(label(t), [copy_tree(b) for b in branches(t)])
复制代码
回复

使用道具 举报

🔗
 楼主| smoothiethu 2019-8-6 12:48:21 | 只看该作者
全局:
Lab05 extra, 有几道题目蛮难的,最后一题搜了答案才想出来。。tree还是蛮难。。

  1. """ Optional questions for Lab 05 """

  2. from lab05 import *

  3. # Shakespeare and Dictionaries
  4. def build_successors_table(tokens):
  5.     """Return a dictionary: keys are words; values are lists of successors.

  6.     >>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
  7.     >>> table = build_successors_table(text)
  8.     >>> sorted(table)
  9.     [',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie', 'to']
  10.     >>> table['to']
  11.     ['investigate', 'eat']
  12.     >>> table['pie']
  13.     ['.']
  14.     >>> table['.']
  15.     ['We']
  16.     """
  17.     table = {}
  18.     prev = '.'
  19.     for word in tokens:
  20.         if prev not in table:
  21.             "*** YOUR CODE HERE ***"
  22.             table[prev] = [tokens[(i + 1)%len(tokens)] for i in range(len(tokens)) if tokens[i] == prev]
  23.         "*** YOUR CODE HERE ***"
  24.         if table[prev] == '.':
  25.             return table
  26.         prev = word
  27.     return table

  28. def construct_sent(word, table):
  29.     """Prints a random sentence starting with word, sampling from
  30.     table.

  31.     >>> table = {'Wow': ['!'], 'Sentences': ['are'], 'are': ['cool'], 'cool': ['.']}
  32.     >>> construct_sent('Wow', table)
  33.     'Wow!'
  34.     >>> construct_sent('Sentences', table)
  35.     'Sentences are cool.'
  36.     """
  37.     import random
  38.     result = ''
  39.     while word not in ['.', '!', '?']:
  40.         "*** YOUR CODE HERE ***"
  41.         result = result + ' ' + word ## 注意printout中有空格
  42.         word = random.choice(table[word])
  43.     return result.strip() + word

  44. def shakespeare_tokens(path='shakespeare.txt', url='http://composingprograms.com/shakespeare.txt'):
  45.     """Return the words of Shakespeare's plays as a list."""
  46.     import os
  47.     from urllib.request import urlopen
  48.     if os.path.exists(path):
  49.         return open('shakespeare.txt', encoding='ascii').read().split()
  50.     else:
  51.         shakespeare = urlopen(url)
  52.         return shakespeare.read().decode(encoding='ascii').split()

  53. # Uncomment the following two lines
  54. tokens = shakespeare_tokens()
  55. table = build_successors_table(tokens)

  56. def random_sent():
  57.     import random
  58.     return construct_sent(random.choice(table['.']), table)

  59. # Q8
  60. def prune_leaves(t, vals):
  61.     """Return a modified copy of t with all leaves that have a label
  62.     that appears in vals removed.  Return None if the entire tree is
  63.     pruned away.

  64.     >>> t = tree(2)
  65.     >>> print(prune_leaves(t, (1, 2)))
  66.     None
  67.     >>> numbers = tree(1, [tree(2), tree(3, [tree(4), tree(5)]), tree(6, [tree(7)])])
  68.     >>> print_tree(numbers)
  69.     1
  70.       2
  71.       3
  72.         4
  73.         5
  74.       6
  75.         7
  76.     >>> print_tree(prune_leaves(numbers, (3, 4, 6, 7)))
  77.     1
  78.       2
  79.       3
  80.         5
  81.       6
  82.     """
  83.     "*** YOUR CODE HERE ***"
  84.     if is_leaf(t):
  85.         if label(t) in vals:
  86.             return None
  87.         else:
  88.             return t
  89.     else:
  90.         new_branches = [prune_leaves(b, vals) for b in branches(t)]
  91.         subtrees = [b for b in new_branches if b is not None] ## 若為None,需要去掉,所以不可以直接用new_branches進行構造tree
  92.         return tree(label(t), subtrees)
  93.         
  94.    

  95. # Q9
  96. def sprout_leaves(t, vals):
  97.     """Sprout new leaves containing the data in vals at each leaf in
  98.     the original tree t and return the resulting tree.

  99.     >>> t1 = tree(1, [tree(2), tree(3)])
  100.     >>> print_tree(t1)
  101.     1
  102.       2
  103.       3
  104.     >>> new1 = sprout_leaves(t1, [4, 5])
  105.     >>> print_tree(new1)
  106.     1
  107.       2
  108.         4
  109.         5
  110.       3
  111.         4
  112.         5

  113.     >>> t2 = tree(1, [tree(2, [tree(3)])])
  114.     >>> print_tree(t2)
  115.     1
  116.       2
  117.         3
  118.     >>> new2 = sprout_leaves(t2, [6, 1, 2])
  119.     >>> print_tree(new2)
  120.     1
  121.       2
  122.         3
  123.           6
  124.           1
  125.           2
  126.     """
  127.     "*** YOUR CODE HERE ***"
  128.     ### the branches should be trees, not just the lists.
  129.     ### Use [tree(x) for x in vals] to create the branches.
  130.     if is_leaf(t):
  131.         return tree(label(t), [tree(x) for x in vals])
  132.     else:
  133.         new_branches = [sprout_leaves(b, vals) for b in branches(t)]
  134.         return tree(label(t), new_branches)
  135.             

  136. # Q10
  137. def add_trees(t1, t2):
  138.     """
  139.     >>> numbers = tree(1,
  140.     ...                [tree(2,
  141.     ...                      [tree(3),
  142.     ...                       tree(4)]),
  143.     ...                 tree(5,
  144.     ...                      [tree(6,
  145.     ...                            [tree(7)]),
  146.     ...                       tree(8)])])
  147.     >>> print_tree(add_trees(numbers, numbers))
  148.     2
  149.       4
  150.         6
  151.         8
  152.       10
  153.         12
  154.           14
  155.         16
  156.     >>> print_tree(add_trees(tree(2), tree(3, [tree(4), tree(5)])))
  157.     5
  158.       4
  159.       5
  160.     >>> print_tree(add_trees(tree(2, [tree(3)]), tree(2, [tree(3), tree(4)])))
  161.     4
  162.       6
  163.       4
  164.     >>> print_tree(add_trees(tree(2, [tree(3, [tree(4), tree(5)])]), \
  165.     tree(2, [tree(3, [tree(4)]), tree(5)])))
  166.     4
  167.       6
  168.         8
  169.         5
  170.       5
  171.     """
  172.     "*** YOUR CODE HERE ***"
  173.     ## Need to find the difference of each branch.
  174.     new_label = label(t1) + label(t2)
  175.     diff = len(branches(t1)) - len(branches(t2))
  176.     if diff > 0:
  177.         new_branches = [add_trees(x, y) for x, y in zip(branches(t1), branches(t2))] + branches(t1)[-diff:]
  178.     elif diff < 0:
  179.         new_branches = [add_trees(x, y) for x, y in zip(branches(t1), branches(t2))] + branches(t2)[diff:]
  180.     else:
  181.         new_branches = [add_trees(x, y) for x, y in zip(branches(t1), branches(t2))]
  182.    
  183.     return tree(new_label, new_branches)

  184.         
  185.         
  186.         
  187.         
  188.         
  189.         
  190.         
  191.         
  192.         
  193.         
  194.    
  195.    
  196.    
  197.    
  198.    
  199.    
复制代码
回复

使用道具 举报

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

本版积分规则

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