📣 VIP通行证夏日特惠 限时立减$68
楼主: lilirr
跳转到指定楼层
上一主题 下一主题
收起左侧

专门开一个帖分享cs61a的答案

 
🔗
 楼主| lilirr 2019-8-3 08:52:21 | 只看该作者
全局:
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('that')
  19.         else:
  20.             print(i)

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

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

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

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

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

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

  74.     >>> berkeley = make_city('Berkeley', 37.87, 112.26)
  75.     >>> stanford = make_city('Stanford', 34.05, 118.25)
  76.     >>> closer_city(38.33, 121.44, berkeley, stanford)
  77.     'Stanford'
  78.     >>> bucharest = make_city('Bucharest', 44.43, 26.10)
  79.     >>> vienna = make_city('Vienna', 48.20, 16.37)
  80.     >>> closer_city(41.29, 174.78, bucharest, vienna)
  81.     'Bucharest'
  82.     """
  83.     "*** YOUR CODE HERE ***"
  84.     distance_12 = distance(city1,city2)
  85.     city3 = make_city('city3',lat,lon)
  86.     if distance(city1,city3)>= distance(city2,city3):
  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]
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-4 23:16:30 | 只看该作者
全局:
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.     def unlst(lst):#因为要循环调用这个功能, 所以用HOF
  17.         flt_ls = []
  18.         for i in lst:
  19.             if type(i) == list:
  20.                 flt_ls += unlst(i)
  21.             else:
  22.                 flt_ls += [i]
  23.         return flt_ls
  24.     return unlst(lst)

  25. # Q7
  26. def merge(lst1, lst2):
  27.     """Merges two sorted lists.

  28.     >>> merge([1, 3, 5], [2, 4, 6])
  29.     [1, 2, 3, 4, 5, 6]
  30.     >>> merge([], [2, 4, 6])
  31.     [2, 4, 6]
  32.     >>> merge([1, 2, 3], [])
  33.     [1, 2, 3]
  34.     >>> merge([5, 7], [2, 4, 6])
  35.     [2, 4, 5, 6, 7]
  36.     """
  37.     "*** YOUR CODE HERE ***"
  38.     #用序列号做对调
  39.     ls = lst1 + lst2
  40.     od = 0 #第一个i的序列号
  41.     for i in ls:
  42.         for m in range(0,len(ls)):
  43.             if i < ls[m]:
  44.                 ls[od], ls[m] = ls[m], ls[od]
  45.         od += 1
  46.     return ls
  47.   
  48. ######################
  49. ### Connect N Game ###
  50. ######################

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

  54.     >>> create_row(5)
  55.     ['-', '-', '-', '-', '-']
  56.     """
  57.     "*** YOUR CODE HERE ***"
  58.     return ['-' for i in range(0,size)]

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

  61.     >>> create_board(3, 5)
  62.     [['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-']]
  63.     """
  64.     "*** YOUR CODE HERE ***"
  65.     return [create_row(columns) for i in range(0,rows)]

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

  69.     >>> old = [1, 2, 3, 4, 5, 6, 7]
  70.     >>> new = replace_elem(old, 2, 8)
  71.     >>> new
  72.     [1, 2, 8, 4, 5, 6, 7]
  73.     >>> new is old   # check that replace_elem outputs a new list
  74.     False
  75.     """
  76.     assert index >= 0 and index < len(lst), 'Index is out of bounds'
  77.     "*** YOUR CODE HERE ***"
  78.     return [lst[i] for i in range(0,index)]+[elem] +[lst[i] for i in range(index+1,len(lst))]

  79. def get_piece(board, row, column):
  80.     """Returns the piece at location (row, column) in the board.
  81.     >>> rows, columns = 2, 2
  82.     >>> board = create_board(rows, columns)
  83.     >>> board = put_piece(board, rows, 0, 'X')[1] # Puts piece "X" in column 0 of board and updates board
  84.     >>> board = put_piece(board, rows, 0, 'O')[1] # Puts piece "O" in column 0 of board and updates board
  85.     >>> get_piece(board, 1, 0)
  86.     'X'
  87.     >>> get_piece(board, 1, 1)
  88.     '-'
  89.     """
  90.     "*** YOUR CODE HERE ***"
  91.     return board[row][column]

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

  95.         1. The index of the row the piece ends up in, or -1 if the column
  96.            is full.
  97.         2. The new board

  98.     >>> rows, columns = 2, 2
  99.     >>> board = create_board(rows, columns)
  100.     >>> row, new_board = put_piece(board, rows, 0, 'X')
  101.     >>> row
  102.     1
  103.     >>> row, new_board = put_piece(new_board, rows, 0, 'O')
  104.     >>> row
  105.     0
  106.     >>> row, new_board = put_piece(new_board, rows, 0, 'X')
  107.     >>> row
  108.     -1
  109.     """
  110.     "*** YOUR CODE HERE ***"
  111.     for i in range(max_rows-1,-1,-1):
  112.         if board[i][column] == '-':
  113.             new_row = replace_elem(board[i],column,player)
  114.             new_bd = replace_elem(board,i,new_row)
  115.             return(i,new_bd)
  116.     return (-1,board)

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

  120.         1. If the move is valid, make_move returns the index of the row the
  121.            piece is placed in. Otherwise, it returns -1.
  122.         2. The updated board

  123.     >>> rows, columns = 2, 2
  124.     >>> board = create_board(rows, columns)
  125.     >>> row, board = make_move(board, rows, columns, 0, 'X')
  126.     >>> row
  127.     1
  128.     >>> get_piece(board, 1, 0)
  129.     'X'
  130.     >>> row, board = make_move(board, rows, columns, 0, 'O')
  131.     >>> row
  132.     0
  133.     >>> row, board = make_move(board, rows, columns, 0, 'X')
  134.     >>> row
  135.     -1
  136.     >>> row, board = make_move(board, rows, columns, -4, '0')
  137.     >>> row
  138.     -1
  139.     """
  140.     "*** YOUR CODE HERE ***"
  141.     if col in range(0,max_cols):
  142.         row, new_board = put_piece(board,max_rows,col,player)
  143.         return(row, new_board)
  144.     else:
  145.         return(-1,board)
  146.         

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

  149.     >>> rows, columns = 2, 2
  150.     >>> board = create_board(rows, columns)
  151.     >>> print_board(board, rows, columns)
  152.     - -
  153.     - -
  154.     >>> new_board = make_move(board, rows, columns, 0, 'X')[1]
  155.     >>> print_board(new_board, rows, columns)
  156.     - -
  157.     X -
  158.     """
  159.     "*** YOUR CODE HERE ***"
  160.     st = ''
  161.     for i in range(0,max_rows):
  162.         if i != max_rows -1: #不加这个最后一行会有一个空格,可以试着把空格替换成其他的更直观看到区别
  163.             for ii in range(0,max_cols):
  164.                 if ii != max_cols -1:
  165.                     st = st + get_piece(board,i,ii) + ' '
  166.                 else:
  167.                     st = st + get_piece(board,i,ii)
  168.             st = st + '\n'
  169.         else:#不加这个else最后一行会有一个\n
  170.             for ii in range(0,max_cols):
  171.                 if ii != max_cols -1:
  172.                     st = st + get_piece(board,i,ii) + ' '
  173.                 else:
  174.                     st = st + get_piece(board,i,ii)
  175.     print(st.strip())
  176. #字符串的打印虽然打出来可能显示一样但机制不同也会报错

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

  180.     >>> rows, columns, num_connect = 4, 4, 2
  181.     >>> board = create_board(rows, columns)
  182.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  183.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  184.     >>> check_win_row(board, rows, columns, num_connect, 3, 'O')
  185.     False
  186.     >>> board = make_move(board, rows, columns, 2, 'X')[1]
  187.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  188.     >>> check_win_row(board, rows, columns, num_connect, 3, 'X')
  189.     False
  190.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  191.     >>> check_win_row(board, rows, columns, num_connect, 3, 'X')
  192.     True
  193.     >>> check_win_row(board, rows, columns, 4, 3, 'X')    # A win depends on the value of num_connect
  194.     False
  195.     >>> check_win_row(board, rows, columns, num_connect, 3, 'O')   # We only detect wins for the given player
  196.     False
  197.     """
  198.     "*** YOUR CODE HERE ***"
  199.     count = 0
  200.     player_st = ''
  201.     row_st = ''
  202.     for i in board[row]:
  203.         row_st += str(i) + ' '
  204.         if i == player:
  205.             count += 1
  206.     if count >= num_connect:
  207.         m = 0
  208.         while m < num_connect:
  209.             player_st += player + ' '
  210.             m += 1
  211.         if player_st in row_st:
  212.             return True
  213.         else:
  214.             
  215.             return False
  216.     else:
  217.         return False
  218.         

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

  222.     >>> rows, columns, num_connect = 5, 5, 2
  223.     >>> board = create_board(rows, columns)
  224.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  225.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  226.     >>> check_win_column(board, rows, columns, num_connect, 0, 'X')
  227.     False
  228.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  229.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  230.     >>> check_win_column(board, rows, columns, num_connect, 1, 'O')
  231.     False
  232.     >>> board = make_move(board, rows, columns, 2, 'X')[1]
  233.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  234.     >>> check_win_column(board, rows, columns, num_connect, 1, 'O')
  235.     True
  236.     >>> check_win_column(board, rows, columns, 4, 1, 'O')
  237.     False
  238.     >>> check_win_column(board, rows, columns, num_connect, 1, 'X')
  239.     False
  240.     """
  241.     "*** YOUR CODE HERE ***"
  242.     count = 0
  243.     player_st = ''
  244.     col_st = ''
  245.     for i in range(0,max_rows):
  246.         col_st += str(board[i][col]) + ' '
  247.         if board[i][col] == player:
  248.             count += 1
  249.     if count >= num_connect:
  250.         m = 0
  251.         while m < num_connect:
  252.             player_st += player + ' '
  253.             m += 1
  254.         if player_st in col_st:
  255.             return True
  256.         else:
  257.             
  258.             return False
  259.     else:
  260.         return False

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

  264.     >>> rows, columns, num_connect = 2, 2, 2
  265.     >>> board = create_board(rows, columns)
  266.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  267.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  268.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  269.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'O')
  270.     False
  271.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  272.     True

  273.     >>> board = create_board(rows, columns)
  274.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  275.     >>> board = make_move(board, rows, columns, 0, 'O')[1]
  276.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  277.     >>> check_win(board, rows, columns, num_connect, 1, 0, 'X')
  278.     True
  279.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  280.     False

  281.     >>> board = create_board(rows, columns)
  282.     >>> board = make_move(board, rows, columns, 0, 'X')[1]
  283.     >>> board = make_move(board, rows, columns, 1, 'O')[1]
  284.     >>> board = make_move(board, rows, columns, 1, 'X')[1]
  285.     >>> check_win(board, rows, columns, num_connect, 0, 0, 'X')
  286.     False
  287.     >>> check_win(board, rows, columns, num_connect, 1, 0, 'X')
  288.     True
  289.     """
  290.     diagonal_win = check_win_diagonal(board, max_rows, max_cols, num_connect,
  291.                                       row, col, player)
  292.     "*** YOUR CODE HERE ***"
  293.     if check_win_column(board, max_rows, max_cols, num_connect, col, player):
  294.         return True
  295.     elif check_win_row(board, max_rows, max_cols, num_connect, row, player):
  296.         return True
  297.     elif check_win_diagonal(board, max_rows, max_cols, num_connect, row, col, player):
  298.         return True
  299.     else:
  300.         return False

  301. ###############################################################
  302. ### Functions for reference when solving the other problems ###
  303. ###############################################################

  304. def check_win_diagonal(board, max_rows, max_cols, num_connect, row, col, player):
  305.     """ Returns True if the given player has a diagonal win passing the spot
  306.     (row, column), and False otherwise.
  307.     """
  308.     # Find top left of diagonal passing through the newly placed piece.
  309.     adjacent = 0
  310.     row_top_left, col_top_left = row, col
  311.     while row_top_left > 0 and col_top_left > 0:
  312.         row_top_left -= 1
  313.         col_top_left -= 1

  314.     # Loop through top left to bottom right diagonal and check for win.
  315.     while row_top_left < max_rows and col_top_left < max_cols:
  316.         piece = get_piece(board, row_top_left, col_top_left)
  317.         if piece == player:
  318.             adjacent += 1
  319.         else:
  320.             adjacent = 0
  321.         if adjacent >= num_connect:
  322.             return True
  323.         row_top_left += 1
  324.         col_top_left += 1

  325.     # Find top right of diagonal passing through the newly placed piece.
  326.     adjacent = 0
  327.     row_top_right, col_top_right = row, col
  328.     while row_top_right > 0 and col_top_right < max_cols - 1:
  329.         row_top_right -= 1
  330.         col_top_right += 1

  331.     # Loop through top right to bottom left diagonal and check for win.
  332.     while row_top_right < max_rows and col_top_right >= 0:
  333.         piece = get_piece(board, row_top_right, col_top_right)
  334.         if piece == player:
  335.             adjacent += 1
  336.         else:
  337.             adjacent = 0
  338.         if adjacent >= num_connect:
  339.             return True
  340.         row_top_right += 1
  341.         col_top_right -= 1

  342.     return False

  343. #####################################################################################
  344. ### You do not need to read or understand the following code for this assignment. ###
  345. #####################################################################################

  346. import sys

  347. def other(player):
  348.     """ Returns the given player's opponent.
  349.     """
  350.     if player == 'X':
  351.         return 'O'
  352.     return 'X'

  353. def play(board, max_rows, max_cols, num_connect):
  354.     max_turns = max_rows * max_cols
  355.     playing = True
  356.     print("Player 'X' starts")
  357.     who = 'X'
  358.     turns = 0

  359.     while True:
  360.         turns += 1
  361.         if turns > max_turns:
  362.             print("No more moves. It's a tie!")
  363.             sys.exit()

  364.         while True:
  365.             try:
  366.                 col_index = int(input('Which column, player {}? '.format(who)))
  367.             except ValueError as e:
  368.                 print('Invalid input. Please try again.')
  369.                 continue

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

  371.             if row_index != -1:
  372.                 break

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

  374.         print_board(board, max_rows, max_cols)

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

  378.         who = other(who)

  379. def start_game():
  380.     # Get all parameters for the game from user.
  381.     while True:
  382.         # Get num_connect from user.
  383.         while True:
  384.             try:
  385.                 num_connect = int(input('How many to connect (e.g. 4 for Connect 4)? '))
  386.             except ValueError as e:
  387.                 print('Invalid input. Please try again.')
  388.                 continue
  389.             break

  390.         # Get number of rows for board from user.
  391.         while True:
  392.             try:
  393.                  max_rows = int(input('How many rows? '))
  394.             except ValueError as e:
  395.                 print('Invalid input. Please try again.')
  396.                 continue
  397.             break

  398.         # Get number of columns for board from user.
  399.         while True:
  400.             try:
  401.                 max_cols = int(input('How many columns? '))
  402.             except ValueError as e:
  403.                 print('Invalid input. Please try again.')
  404.                 continue
  405.             break

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

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

使用道具 举报

🔗
 楼主| lilirr 2019-8-7 21:02:29 | 只看该作者
全局:
project02: yelp maps

abstraction:
  1. """Data Abstractions"""

  2. from utils import mean

  3. #############################
  4. # Phase 1: Data Abstraction #
  5. #############################


  6. # Reviews

  7. def make_review(restaurant_name, rating):
  8.     """Return a review data abstraction."""
  9.     return [restaurant_name, rating]

  10. def review_restaurant_name(review):
  11.     """Return the restaurant name of the review, which is a string."""
  12.     return review[0]

  13. def review_rating(review):
  14.     """Return the number of stars given by the review, which is a
  15.     floating point number between 1 and 5."""
  16.     return review[1]   


  17. # Users

  18. def make_user(name, reviews):
  19.     """Return a user data abstraction."""
  20.     return [name, {review_restaurant_name(r): r for r in reviews}]

  21. def user_name(user):
  22.     """Return the name of the user, which is a string."""
  23.     return user[0]

  24. def user_reviews(user):
  25.     """Return a dictionary from restaurant names to reviews by the user."""
  26.     return user[1]


  27. ### === +++ USER ABSTRACTION BARRIER +++ === ###

  28. def user_reviewed_restaurants(user, restaurants):
  29.     """Return the subset of restaurants reviewed by user.

  30.     Arguments:
  31.     user -- a user
  32.     restaurants -- a list of restaurant data abstractions
  33.     """
  34.     names = list(user_reviews(user))
  35.     return [r for r in restaurants if restaurant_name(r) in names]

  36. def user_rating(user, restaurant_name):
  37.     """Return the rating given for restaurant_name by user."""
  38.     reviewed_by_user = user_reviews(user)
  39.     user_review = reviewed_by_user[restaurant_name]
  40.     return review_rating(user_review)


  41. # Restaurants

  42. def make_restaurant(name, location, categories, price, reviews):
  43.     """Return a restaurant data abstraction containing the name, location,
  44.     categories, price, and reviews for that restaurant."""
  45.     # BEGIN Question 2
  46.     "*** YOUR CODE HERE ***"
  47.     res = {'resnm':name,'resloc':location,'rescate':categories,'respri':price,'resrev':reviews}
  48.     return res
  49.     # END Question 2

  50. def restaurant_name(restaurant):
  51.     """Return the name of the restaurant, which is a string."""
  52.     # BEGIN Question 2
  53.     "*** YOUR CODE HERE ***"
  54.     return restaurant['resnm']
  55.     # END Question 2

  56. def restaurant_location(restaurant):
  57.     """Return the location of the restaurant, which is a list containing
  58.     latitude and longitude."""
  59.     # BEGIN Question 2
  60.     "*** YOUR CODE HERE ***"
  61.     return restaurant['resloc']
  62.     # END Question 2

  63. def restaurant_categories(restaurant):
  64.     """Return the categories of the restaurant, which is a list of strings."""
  65.     # BEGIN Question 2
  66.     "*** YOUR CODE HERE ***"
  67.     return restaurant['rescate']
  68.     # END Question 2

  69. def restaurant_price(restaurant):
  70.     """Return the price of the restaurant, which is a number."""
  71.     # BEGIN Question 2
  72.     "*** YOUR CODE HERE ***"
  73.     return restaurant['respri']
  74.     # END Question 2

  75. def restaurant_ratings(restaurant):
  76.     """Return a list of ratings, which are numbers from 1 to 5, of the
  77.     restaurant based on the reviews of the restaurant."""
  78.     # BEGIN Question 2
  79.     "*** YOUR CODE HERE ***"
  80.     rt = []
  81.     for i in restaurant['resrev']:
  82.         rt += [review_rating(i)] #i就是['name',4]这种review
  83.     return rt
  84.     # END Question 2
复制代码


recommend
  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 x :distance(location,x))
  19.     #一个疑问,下面的代码哪里错了?
  20.     #之前的代码是return [min(center, key = lambda x :distance(location,x)) for center in centroids]            
  21.     # END Question 3


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

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

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


  36. def group_by_centroid(restaurants, centroids):
  37.     """Return a list of clusters, where each cluster contains all restaurants
  38.     nearest to a corresponding centroid in centroids. Each item in
  39.     restaurants should appear once in the result, along with the other
  40.     restaurants closest to the same centroid.
  41.     """
  42.     # BEGIN Question 4
  43.     "*** YOUR CODE HERE ***"
  44.     ls = []
  45.     for restaurant in restaurants:
  46.         location = restaurant_location(restaurant)
  47.         #min里面的东西应该是一个序列,我差点又犯错了 = =
  48.         ls.append([min(centroids, key = lambda x :distance(x,location)),restaurant])
  49.     return group_by_first(ls)#返回的是同一centroid的restaurant的集合的集合
  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.     lat,lon = [],[]
  56.     for restaurant in cluster:
  57.         lat += [restaurant_location(restaurant)[0]]
  58.         lon += [restaurant_location(restaurant)[1]]
  59.     return [mean(lat),mean(lon)]
  60.     # END Question 5


  61. def k_means(restaurants, k, max_updates=100):
  62.     """Use k-means to group restaurants by location into k clusters."""
  63.     assert len(restaurants) >= k, 'Not enough restaurants to cluster'
  64.     old_centroids, n = [], 0
  65.     # Select initial centroids randomly by choosing k different restaurants
  66.     centroids = [restaurant_location(r) for r in sample(restaurants, k)]
  67.     while old_centroids != centroids and n < max_updates:
  68.         old_centroids = centroids
  69.         # BEGIN Question 6
  70.         "*** YOUR CODE HERE ***"
  71.         cluster = group_by_centroid(restaurants,centroids)
  72.         centroids = [find_centroid(single_cluster) for single_cluster in cluster]
  73.         '''
  74.         1.随机选取中心点
  75.         2.先用已有的中心点把每个餐馆聚类
  76.         3.更新每个聚类的中心点
  77.         '''
  78.         #一定要注意边界! 否则会做重复工作
  79.         # END Question 6
  80.         n += 1
  81.     return centroids


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


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

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

  96.     xs = [feature_fn(r) for r in restaurants]
  97.     ys = [reviews_by_user[restaurant_name(r)] for r in restaurants]
  98.    
  99.     # BEGIN Question 7
  100.     Sxx,Syy,Sxy = 0,0,0
  101.     pairs = zip(xs, ys)
  102.     s_xx, s_yy, s_xy = 0, 0, 0
  103.     for x, y in pairs:
  104.         s_xx += (x - mean(xs)) ** 2
  105.         s_yy += (y - mean(ys)) ** 2
  106.         s_xy += (x - mean(xs)) * (y - mean(ys))
  107.     b = s_xy / s_xx
  108.     a = mean(ys) - b * mean(xs)
  109.     r_squared = (s_xy ** 2) / (s_xx * s_yy)
  110.    
  111.     def predictor(restaurant):
  112.         return a+b*feature_fn(restaurant)
  113.    
  114.     return predictor, r_squared
  115.     #为什么下面这个代码是错的?
  116.    
  117.     '''Sxx,Syy,Sxy = 0,0,0
  118.     for i in range(len(xs)):
  119.         Sxx += (xs[i]-mean(xs))**2
  120.         Syy += (ys[i]-mean(ys))**2
  121.         Sxy += (xs[i]-mean(xs))*(ys[i]-mean(ys))
  122.     b = Sxy/Sxx,
  123.     a = mean(ys) - b*mean(xs)
  124.     r_squared = Sxy**2/(Sxx*Syy)
  125.     def predictor(restaurant):
  126.         return a+b*feature_fn(restaurant)
  127.    
  128.     return predictor, r_squared'''
  129.    
  130.     # END Question 7
  131.    
  132.     def predictor(restaurant):
  133.         return b * feature_fn(restaurant) + a

  134.     return predictor, r_squared


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

  138.     Arguments:
  139.     user -- A user
  140.     restaurants -- A list of restaurants
  141.     feature_fns -- A sequence of functions that each takes a restaurant
  142.     """
  143.     reviewed = user_reviewed_restaurants(user, restaurants)
  144.     # BEGIN Question 8
  145.     "*** YOUR CODE HERE ***"
  146.    
  147.     pred_rat = {find_predictor(user, reviewed, feature_fn)[0]: find_predictor(user, reviewed, feature_fn)[1]
  148.                 for feature_fn in feature_fns}
  149.     return max(pred_rat, key = lambda keys: pred_rat[keys])
  150.     #区分字典单独出现和字典有selector的区别
  151.     # END Question 8


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

  155.     Arguments:
  156.     user -- A user
  157.     restaurants -- A list of restaurants
  158.     feature_fns -- A sequence of feature functions
  159.     """
  160.     predictor = best_predictor(user, ALL_RESTAURANTS, feature_fns)
  161.     reviewed = user_reviewed_restaurants(user, restaurants)
  162.     # BEGIN Question 9
  163.     "*** YOUR CODE HERE ***"
  164.     rate_dic = []
  165.     for restaurant in restaurants:
  166.         if restaurant not in reviewed:
  167.             rate_dic.append([restaurant_name(restaurant),predictor(restaurant)])
  168.         else:
  169.             rate_dic.append([restaurant_name(restaurant),user_rating(user, restaurant_name(restaurant))])
  170.     return dict(rate_dic)
  171.     # END Question 9


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

  174.     Arguments:
  175.     query -- A string
  176.     restaurants -- A sequence of restaurants
  177.     """
  178.     # BEGIN Question 10
  179.     "*** YOUR CODE HERE ***"
  180.     return [restaurant for restaurant in restaurants if (query in restaurant_categories(restaurant))]
  181.     # END Question 10


  182. def feature_set():
  183.     """Return a sequence of feature functions."""
  184.     return [lambda r: mean(restaurant_ratings(r)),
  185.             restaurant_price,
  186.             lambda r: len(restaurant_ratings(r)),
  187.             lambda r: restaurant_location(r)[0],
  188.             lambda r: restaurant_location(r)[1]]


  189. @main
  190. def main(*args):
  191.     import argparse
  192.     parser = argparse.ArgumentParser(
  193.         description='Run Recommendations',
  194.         formatter_class=argparse.RawTextHelpFormatter
  195.     )
  196.     parser.add_argument('-u', '--user', type=str, choices=USER_FILES,
  197.                         default='test_user',
  198.                         metavar='USER',
  199.                         help='user file, e.g.\n' +
  200.                         '{{{}}}'.format(','.join(sample(USER_FILES, 3))))
  201.     parser.add_argument('-k', '--k', type=int, help='for k-means')
  202.     parser.add_argument('-q', '--query', choices=CATEGORIES,
  203.                         metavar='QUERY',
  204.                         help='search for restaurants by category e.g.\n'
  205.                         '{{{}}}'.format(','.join(sample(CATEGORIES, 3))))
  206.     parser.add_argument('-p', '--predict', action='store_true',
  207.                         help='predict ratings for all restaurants')
  208.     parser.add_argument('-r', '--restaurants', action='store_true',
  209.                         help='outputs a list of restaurant names')
  210.     args = parser.parse_args()

  211.     # Output a list of restaurant names
  212.     if args.restaurants:
  213.         print('Restaurant names:')
  214.         for restaurant in sorted(ALL_RESTAURANTS, key=restaurant_name):
  215.             print(repr(restaurant_name(restaurant)))
  216.         exit(0)

  217.     # Select restaurants using a category query
  218.     if args.query:
  219.         restaurants = search(args.query, ALL_RESTAURANTS)
  220.     else:
  221.         restaurants = ALL_RESTAURANTS

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

  225.     # Collect ratings
  226.     if args.predict:
  227.         ratings = rate_all(user, restaurants, feature_set())
  228.     else:
  229.         restaurants = user_reviewed_restaurants(user, restaurants)
  230.         names = [restaurant_name(r) for r in restaurants]
  231.         ratings = {name: user_rating(user, name) for name in names}

  232.     # Draw the visualization
  233.     if args.k:
  234.         centroids = k_means(restaurants, min(args.k, len(restaurants)))
  235.     else:
  236.         centroids = [restaurant_location(r) for r in restaurants]
  237.     draw_map(centroids, restaurants, ratings)
复制代码


utils

  1. """Utilities for Maps"""

  2. from math import sqrt
  3. from random import sample

  4. # Rename the built-in zip ([url]http://docs.python.org/3/library/functions.html#zip[/url])
  5. _zip = zip

  6. def map_and_filter(s, map_fn, filter_fn):
  7.     """Returns a new list containing the results of calling map_fn on each
  8.     element of sequence s for which filter_fn returns a true value.

  9.     >>> square = lambda x: x * x
  10.     >>> is_odd = lambda x: x % 2 == 1
  11.     >>> map_and_filter([1, 2, 3, 4, 5], square, is_odd)
  12.     [1, 9, 25]
  13.     """
  14.     # BEGIN Question 0
  15.     return [map_fn(i) for i in s if filter_fn(i)]
  16.     # END Question 0

  17. def key_of_min_value(d):
  18.     """Returns the key in a dict d that corresponds to the minimum value of d.

  19.     >>> letters = {'a': 6, 'b': 5, 'c': 4, 'd': 5}
  20.     >>> min(letters)
  21.     'a'
  22.     >>> key_of_min_value(letters)
  23.     'c'
  24.     """
  25.     # BEGIN Question 0
  26.     return min(d,key = lambda x : d[x]) #d[x]中的x是d中的元素,所以d[x]就是values
  27.     # END Question 0

  28. def zip(*sequences):
  29.     """Returns a list of lists, where the i-th list contains the i-th
  30.     element from each of the argument sequences.

  31.     >>> zip(range(0, 3), range(3, 6))
  32.     [[0, 3], [1, 4], [2, 5]]
  33.     >>> for a, b in zip([1, 2, 3], [4, 5, 6]):
  34.     ...     print(a, b)
  35.     1 4
  36.     2 5
  37.     3 6
  38.     >>> for triple in zip(['a', 'b', 'c'], [1, 2, 3], ['do', 're', 'mi']):
  39.     ...     print(triple)
  40.     ['a', 1, 'do']
  41.     ['b', 2, 're']
  42.     ['c', 3, 'mi']
  43.     """
  44.     return list(map(list, _zip(*sequences)))

  45. def enumerate(s, start=0):
  46.     """Returns a list of lists, where the i-th list contains i+start and
  47.     the i-th element of s.

  48.     >>> enumerate([6, 1, 'a'])
  49.     [[0, 6], [1, 1], [2, 'a']]
  50.     >>> enumerate('five', 5)
  51.     [[5, 'f'], [6, 'i'], [7, 'v'], [8, 'e']]
  52.     """
  53.     # BEGIN Question 0
  54.     "*** YOUR CODE HERE ***"
  55.     return zip([i+start for i in range(0,len(s))],s)
  56.     # END Question 0

  57. def distance(pos1, pos2):
  58.     """Returns the Euclidean distance between pos1 and pos2, which are pairs.

  59.     >>> distance([1, 2], [4, 6])
  60.     5.0
  61.     """
  62.     return sqrt((pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2)

  63. def mean(s):
  64.     """Returns the arithmetic mean of a sequence of numbers s.

  65.     >>> mean([-1, 3])
  66.     1.0
  67.     >>> mean([0, -3, 2, -1])
  68.     -0.5
  69.     """
  70.     # BEGIN Question 1
  71.     "*** YOUR CODE HERE ***"
  72.     assert s != []
  73.     total = 0
  74.     for i in s:
  75.         total += i
  76.     return total/len(s)
  77.     # END Question 1
复制代码

回复

使用道具 举报

🔗
czahie 2019-8-9 10:20:33 | 只看该作者
全局:
lilirr 发表于 2019-7-27 10:55
在github上找,每一个都有答案
一个参考

哈哈哈这是我的仓库 = =
回复

使用道具 举报

🔗
lentebloem 2019-8-11 21:26:34 | 只看该作者
全局:
表扬楼主积极学习分享的精神!
不过不知道楼主看没看过https://www.1point3acres.com/bbs/thread-37823-1-1.html关于Honor Code的帖子
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-12 12:41:33 | 只看该作者
全局:
hw05(不包括extra,因为我在赶进度所以extra先略过了)

  1. 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.         return t #这一步很关键啊
  91.     else:
  92.         return tree(label(t),[replace_leaf(branch,old,new)for branch in branches(t)])
  93.             
  94. def print_move(origin, destination):
  95.     """Print instructions to move a disk."""
  96.     print("Move the top disk from rod", origin, "to rod", destination)

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

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

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

  106.     >>> move_stack(1, 1, 3)
  107.     Move the top disk from rod 1 to rod 3
  108.     >>> move_stack(2, 1, 3)
  109.     Move the top disk from rod 1 to rod 2
  110.     Move the top disk from rod 1 to rod 3
  111.     Move the top disk from rod 2 to rod 3
  112.     >>> move_stack(3, 1, 3)
  113.     Move the top disk from rod 1 to rod 3
  114.     Move the top disk from rod 1 to rod 2
  115.     Move the top disk from rod 3 to rod 2
  116.     Move the top disk from rod 1 to rod 3
  117.     Move the top disk from rod 2 to rod 1
  118.     Move the top disk from rod 2 to rod 3
  119.     Move the top disk from rod 1 to rod 3
  120.     """
  121.     assert 1 <= start <= 3 and 1 <= end <= 3 and start != end, "Bad start/end"
  122.     "*** YOUR CODE HERE ***"
  123.     #核心思想是把start上面n-1个移到auxiliary pole上,再把start上剩余的第n个移到end上。重复进行
  124.     auxiliary = 6-start-end
  125.     if n ==1:
  126.         print_move(start,end)
  127.     else:
  128.         move_stack(n-1,start,auxiliary)
  129.         print_move(start,end)
  130.         move_stack(n-1,auxiliary,end)
  131. ###########
  132. # Mobiles #
  133. ###########

  134. def mobile(left, right):
  135.     """Construct a mobile from a left side and a right side."""
  136.     return tree('mobile', [left, right])

  137. def is_mobile(m):
  138.     return is_tree(m) and label(m) == 'mobile'

  139. def sides(m):
  140.     """Select the sides of a mobile."""
  141.     assert is_mobile(m), "must call sides on a mobile"
  142.     return branches(m)

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

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

  148. def length(s):
  149.     """Select the length of a side."""
  150.     assert is_side(s), "must call length on a side"
  151.     return label(s)

  152. def end(s):
  153.     """Select the mobile or weight hanging at the end of a side."""
  154.     assert is_side(s), "must call end on a side"
  155.     return branches(s)[0]

  156. def weight(size):
  157.     """Construct a weight of some size."""
  158.     assert size > 0
  159.     "*** YOUR CODE HERE ***"
  160.     #tree的branch也必须是tree类型,注意label不一定是str类型
  161.     return tree(size,[])

  162. def size(w):
  163.     """Select the size of a weight."""
  164.     "*** YOUR CODE HERE ***"
  165.     assert is_weight(w)
  166.     return label(w)

  167. def is_weight(w):
  168.     """Whether w is a weight, not a mobile."""
  169.     "*** YOUR CODE HERE ***"
  170.     return not is_mobile(w) and type(label(w))==int and branches(w)==[]

  171. def examples():
  172.     t = mobile(side(1, weight(2)),
  173.                side(2, weight(1)))
  174.     u = mobile(side(5, weight(1)),
  175.                side(1, mobile(side(2, weight(3)),
  176.                               side(3, weight(2)))))
  177.     v = mobile(side(4, t), side(2, u))
  178.     return (t, u, v)


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

  181.     >>> t, u, v = examples()
  182.     >>> total_weight(t)
  183.     3
  184.     >>> total_weight(u)
  185.     6
  186.     >>> total_weight(v)
  187.     9
  188.     """
  189.     if is_weight(m):
  190.         return size(m)
  191.     else:
  192.         assert is_mobile(m), "must get total weight of a mobile or a weight"
  193.         return sum([total_weight(end(s)) for s in sides(m)])

  194. def balanced(m):
  195.     """Return whether m is balanced.

  196.     >>> t, u, v = examples()
  197.     >>> balanced(t)
  198.     True
  199.     >>> balanced(v)
  200.     True
  201.     >>> w = mobile(side(3, t), side(2, u))
  202.     >>> balanced(w)
  203.     False
  204.     >>> balanced(mobile(side(1, v), side(1, w)))
  205.     False
  206.     >>> balanced(mobile(side(1, w), side(1, v)))
  207.     False
  208.     """
  209.     "*** YOUR CODE HERE ***"
  210.     for side in sides(m):
  211.         #sides(m)返回的m的branches[left,right],所以side是个tree
  212.         if is_mobile(end(side)) and not balanced(end(side)):#这一步容易错,对照balanced(mobile(side(1, v), side(1, w))),submobile v,w也必须是平衡的
  213.             return False
  214.     weight0,weight1 = total_weight(end(sides(m)[0])),total_weight(end(sides(m)[1]))
  215.     return weight0*length(sides(m)[0]) == weight1*length(sides(m)[1])
  216.             

  217. #######
  218. # OOP #
  219. #######

  220. class Account:
  221.     """An account has a balance and a holder.

  222.     >>> a = Account('John')
  223.     >>> a.deposit(10)
  224.     10
  225.     >>> a.balance
  226.     10
  227.     >>> a.interest
  228.     0.02

  229.     >>> a.time_to_retire(10.25) # 10 -> 10.2 -> 10.404
  230.     2
  231.     >>> a.balance               # balance should not change
  232.     10
  233.     >>> a.time_to_retire(11)    # 10 -> 10.2 -> ... -> 11.040808032
  234.     5
  235.     >>> a.time_to_retire(100)
  236.     117
  237.     """

  238.     interest = 0.02  # A class attribute

  239.     def __init__(self, account_holder):
  240.         self.holder = account_holder
  241.         self.balance = 0

  242.     def deposit(self, amount):
  243.         """Add amount to balance."""
  244.         self.balance = self.balance + amount
  245.         return self.balance

  246.     def withdraw(self, amount):
  247.         """Subtract amount from balance if funds are available."""
  248.         if amount > self.balance:
  249.             return 'Insufficient funds'
  250.         self.balance = self.balance - amount
  251.         return self.balance

  252.     def time_to_retire(self, amount):
  253.         """Return the number of years until balance would grow to amount."""
  254.         assert self.balance > 0 and amount > 0 and self.interest > 0
  255.         "*** YOUR CODE HERE ***"
  256.         future_salary = self.balance
  257.         year = 0
  258.         while future_salary < amount:
  259.             future_salary = future_salary * (1+self.interest)
  260.             year += 1
  261.         return year

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

  264.     >>> ch = FreeChecking('Jack')
  265.     >>> ch.balance = 20
  266.     >>> ch.withdraw(100)  # First one's free
  267.     'Insufficient funds'
  268.     >>> ch.withdraw(3)    # And the second
  269.     17
  270.     >>> ch.balance
  271.     17
  272.     >>> ch.withdraw(3)    # Ok, two free withdrawals is enough
  273.     13
  274.     >>> ch.withdraw(3)
  275.     9
  276.     >>> ch2 = FreeChecking('John')
  277.     >>> ch2.balance = 10
  278.     >>> ch2.withdraw(3) # No fee
  279.     7
  280.     >>> ch.withdraw(3)  # ch still charges a fee
  281.     5
  282.     >>> ch.withdraw(5)  # Not enough to cover fee + withdraw
  283.     'Insufficient funds'
  284.     """
  285.     withdraw_fee = 1
  286.     free_withdrawals = 2

  287.     "*** YOUR CODE HERE ***"
  288.     def withdraw(self, amount):
  289.         self.free_withdrawals -= 1
  290.         if self.free_withdrawals >= 0:
  291.             return Account.withdraw(self,amount)
  292.         else:
  293.             if amount+self.withdraw_fee > self.balance:
  294.                 return 'Insufficient funds'
  295.             self.balance = self.balance - amount - self.withdraw_fee
  296.             return self.balance

  297. ############
  298. # Mutation #
  299. ############

  300. def make_counter():
  301.     """Return a counter function.

  302.     >>> c = make_counter()
  303.     >>> c('a')
  304.     1
  305.     >>> c('a')
  306.     2
  307.     >>> c('b')
  308.     1
  309.     >>> c('a')
  310.     3
  311.     >>> c2 = make_counter()
  312.     >>> c2('b')
  313.     1
  314.     >>> c2('b')
  315.     2
  316.     >>> c('b') + c2('b')
  317.     5
  318.     """
  319.     "*** YOUR CODE HERE ***"
  320.     memory = []
  321.     appear_times = []
  322.     def counter(string):
  323.         nonlocal memory
  324.         nonlocal appear_times
  325.         if string not in memory:
  326.             memory.append(string)
  327.             appear_times.append(1)
  328.             indx = memory.index(string)
  329.         else:
  330.             indx = memory.index(string)
  331.             appear_times[indx] += 1
  332.         return appear_times[indx]
  333.     return counter

  334. def make_fib():
  335.     """Returns a function that returns the next Fibonacci number
  336.     every time it is called.

  337.     >>> fib = make_fib()
  338.     >>> fib()
  339.     0
  340.     >>> fib()
  341.     1
  342.     >>> fib()
  343.     1
  344.     >>> fib()
  345.     2
  346.     >>> fib()
  347.     3
  348.     >>> fib2 = make_fib()
  349.     >>> fib() + sum([fib2() for _ in range(5)])
  350.     12
  351.     """
  352.     "*** YOUR CODE HERE ***"
  353.     call_times_m1 = 0
  354.     last_two = 0
  355.     last = 0
  356.     def fib_num():
  357.         nonlocal call_times_m1
  358.         nonlocal last_two
  359.         nonlocal last
  360.         if call_times_m1 == 0:
  361.             call_times_m1 +=1
  362.             return 0
  363.         elif call_times_m1 ==1:
  364.             last_two,last = 0, 1
  365.             call_times_m1 +=1
  366.             return 1
  367.         else:
  368.             last,last_two = last+last_two,last
  369.             call_times_m1 +=1
  370.         return last
  371.     return fib_num

  372. def make_withdraw(balance, password):
  373.     """Return a password-protected withdraw function.
  374.     >>> w = make_withdraw(100, 'hax0r')
  375.     >>> w(25, 'hax0r')
  376.     75
  377.     >>> error = w(90, 'hax0r')
  378.     >>> error
  379.     'Insufficient funds'
  380.     >>> error = w(25, 'hwat')
  381.     >>> error
  382.     'Incorrect password'
  383.     >>> new_bal = w(25, 'hax0r')
  384.     >>> new_bal
  385.     50
  386.     >>> w(75, 'a')
  387.     'Incorrect password'
  388.     >>> w(10, 'hax0r')
  389.     40
  390.     >>> w(20, 'n00b')
  391.     'Incorrect password'
  392.     >>> w(10, 'hax0r')
  393.     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"
  394.     >>> w(10, 'l33t')
  395.     "Your account is locked. Attempts: ['hwat', 'a', 'n00b']"
  396.     >>> type(w(10, 'l33t')) == str
  397.     True
  398.     """
  399.     "*** YOUR CODE HERE ***"
  400.     incorrect_pw = []
  401.     def withdraw(amount,input_pw):
  402.         nonlocal balance,incorrect_pw
  403.         if len(incorrect_pw) >= 3:
  404.             return "Your account is locked. Attempts: " + str(incorrect_pw)
  405.         elif input_pw != password and input_pw not in incorrect_pw:
  406.             incorrect_pw.append(input_pw)
  407.             return "Incorrect password"
  408.         elif input_pw != password and input_pw in incorrect_pw:
  409.             return "Incorrect password"
  410.         else:
  411.             if amount > balance:
  412.                 return "Insufficient funds"
  413.             balance = balance - amount
  414.         return balance
  415.     return withdraw

  416. #好好复习这道题,难,并且陷阱很多,不敢相信我居然卡了三个小时  = = ...
  417. def make_joint(withdraw, old_password, new_password):
  418.     """Return a password-protected withdraw function that has joint access to
  419.     the balance of withdraw.

  420.     >>> w = make_withdraw(100, 'hax0r')
  421.     >>> w(25, 'hax0r')
  422.     75
  423.     >>> make_joint(w, 'my', 'secret')
  424.     'Incorrect password'
  425.     >>> j = make_joint(w, 'hax0r', 'secret')
  426.     >>> w(25, 'secret')
  427.     'Incorrect password'
  428.     >>> j(25, 'secret')
  429.     50
  430.     >>> j(25, 'hax0r')
  431.     25
  432.     >>> j(100, 'secret')
  433.     'Insufficient funds'

  434.     >>> j2 = make_joint(j, 'secret', 'code')
  435.     >>> j2(5, 'code')
  436.     20
  437.     >>> j2(5, 'secret')
  438.     15
  439.     >>> j2(5, 'hax0r')
  440.     10

  441.     >>> j2(25, 'password')
  442.     'Incorrect password'
  443.     >>> j2(5, 'secret')
  444.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  445.     >>> j(5, 'secret')
  446.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  447.     >>> w(5, 'hax0r')
  448.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  449.     >>> make_joint(w, 'hax0r', 'hello')
  450.     "Your account is locked. Attempts: ['my', 'secret', 'password']"
  451.     """
  452.     "*** YOUR CODE HERE ***"

  453.    
  454.     correct_passwords = [old_password,new_password]
  455.     def jointed(amount,user_password):#这个user_password这里卡了
  456.         if user_password in correct_passwords:
  457.             return withdraw(amount,old_password)
  458.         else:
  459.             return withdraw(amount,user_password)
  460.     if type(withdraw(0,old_password)) != str: #密码对上了
  461.              return jointed #直接返回密码正确的withdraw,功能同上
  462.     else:
  463.         return withdraw(0,old_password) #密码错误的功能用已定义的实现(很巧妙!!)'''
  464.    

  465. ###################
  466. # Extra Questions #
  467. ###################

  468. def interval(a, b):
  469.     """Construct an interval from a to b."""
  470.     return [a, b]

  471. def lower_bound(x):
  472.     """Return the lower bound of interval x."""
  473.     "*** YOUR CODE HERE ***"

  474. def upper_bound(x):
  475.     """Return the upper bound of interval x."""
  476.     "*** YOUR CODE HERE ***"

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

  480. def add_interval(x, y):
  481.     """Return an interval that contains the sum of any value in interval x and
  482.     any value in interval y."""
  483.     lower = lower_bound(x) + lower_bound(y)
  484.     upper = upper_bound(x) + upper_bound(y)
  485.     return interval(lower, upper)

  486. def mul_interval(x, y):
  487.     """Return the interval that contains the product of any value in x and any
  488.     value in y."""
  489.     p1 = x[0] * y[0]
  490.     p2 = x[0] * y[1]
  491.     p3 = x[1] * y[0]
  492.     p4 = x[1] * y[1]
  493.     return [min(p1, p2, p3, p4), max(p1, p2, p3, p4)]

  494. def sub_interval(x, y):
  495.     """Return the interval that contains the difference between any value in x
  496.     and any value in y."""
  497.     "*** YOUR CODE HERE ***"

  498. def div_interval(x, y):
  499.     """Return the interval that contains the quotient of any value in x divided by
  500.     any value in y. Division is implemented as the multiplication of x by the
  501.     reciprocal of y."""
  502.     "*** YOUR CODE HERE ***"
  503.     reciprocal_y = interval(1/upper_bound(y), 1/lower_bound(y))
  504.     return mul_interval(x, reciprocal_y)

  505. def par1(r1, r2):
  506.     return div_interval(mul_interval(r1, r2), add_interval(r1, r2))

  507. def par2(r1, r2):
  508.     one = interval(1, 1)
  509.     rep_r1 = div_interval(one, r1)
  510.     rep_r2 = div_interval(one, r2)
  511.     return div_interval(one, add_interval(rep_r1, rep_r2))

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

  514.     >>> r1, r2 = check_par()
  515.     >>> x = par1(r1, r2)
  516.     >>> y = par2(r1, r2)
  517.     >>> lower_bound(x) != lower_bound(y) or upper_bound(x) != upper_bound(y)
  518.     True
  519.     """
  520.     r1 = interval(1, 1) # Replace this line!
  521.     r2 = interval(1, 1) # Replace this line!
  522.     return r1, r2

  523. def multiple_references_explanation():
  524.     return """The multiple reference problem..."""

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

  528.     >>> str_interval(quadratic(interval(0, 2), -2, 3, -1))
  529.     '-3 to 0.125'
  530.     >>> str_interval(quadratic(interval(1, 3), 2, -3, 1))
  531.     '0 to 10'
  532.     """
  533.     "*** YOUR CODE HERE ***"

  534. def polynomial(x, c):
  535.     """Return the interval that is the range of the polynomial defined by
  536.     coefficients c, for domain interval x.

  537.     >>> str_interval(polynomial(interval(0, 2), [-1, 3, -2]))
  538.     '-3 to 0.125'
  539.     >>> str_interval(polynomial(interval(1, 3), [1, -3, 2]))
  540.     '0 to 10'
  541.     >>> str_interval(polynomial(interval(0.5, 2.25), [10, 24, -6, -8, 3]))
  542.     '18.0 to 23.0'
  543.     """
  544.     "*** YOUR CODE HERE ***"

复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-13 11:25:01 | 只看该作者
全局:
lab05和hw05重复太多了,我就没写 直接上的lab06 which is really fun
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-13 11:25:25 | 只看该作者
全局:
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.         self.backpack = []

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

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


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

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



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

  118.     def unlock(self, place):
  119.         """If player has a key, unlock a locked neighboring place.
  120.         >>> key = Key('SkeletonKey', 'A Key to unlock all doors.')
  121.         >>> gbc = Place('GBC', 'You are at Golden Bear Cafe', [], [key])
  122.         >>> fsm = Place('FSM', 'Home of the nectar of the gods', [], [])
  123.         >>> gbc.add_exits([fsm])
  124.         >>> fsm.locked = True
  125.         >>> me = Player('Player', gbc)
  126.         >>> me.unlock(fsm)
  127.         Place must be a string
  128.         >>> me.go_to('FSM')
  129.         FSM is locked! Go look for a key to unlock it
  130.         You are at GBC
  131.         >>> me.unlock(fsm)
  132.         Place must be a string
  133.         >>> me.unlock('FSM')
  134.         FSM can't be unlocked without a key!
  135.         >>> me.take('SkeletonKey')
  136.         Player takes the SkeletonKey
  137.         >>> me.unlock('FSM')
  138.         FSM is now unlocked!
  139.         >>> me.unlock('FSM')
  140.         FSM is already unlocked!
  141.         >>> me.go_to('FSM')
  142.         You are at FSM
  143.         """
  144.         if type(place) != str:
  145.             print("Place must be a string")
  146.             return
  147.         key = None
  148.         for item in self.backpack:
  149.             if type(item) == Key:
  150.                 key = item
  151.         
  152.         place = self.place.get_neighbor(place)#变成了obj
  153.         if not key and place.locked:
  154.             print(place.name + ' can\'t be unlocked without a key!')
  155.         elif not place.locked:
  156.             print(place.name + ' is already unlocked!')
  157.         else:   
  158.             key.use(place)
  159.             print(place.name + ' is now unlocked!')

  160. class Character(object):
  161.     def __init__(self, name, message):
  162.         self.name = name
  163.         self.message = message

  164.     def talk(self):
  165.         return self.message


  166. class Thing(object):
  167.     def __init__(self, name, description):
  168.         self.name = name
  169.         self.description = description

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

  172. """ Implement Key here! """
  173. class Key(Thing):
  174.     def use(self,place):
  175.         place.locked = False

  176. class Treasure(Thing):
  177.     def __init__(self, name, description, value, weight):
  178.         Thing.__init__(self, name, description)
  179.         self.value = value
  180.         self.weight = weight

  181. class Place(object):
  182.     def __init__(self, name, description, characters, things):
  183.         self.name = name
  184.         self.description = description
  185.         self.characters = {character.name: character for character in characters}
  186.         self.things = {thing.name: thing for thing in things}
  187.         self.locked = False
  188.         self.exits = {} # {'name': (exit, 'description')}

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

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

  228.     def take(self, thing):
  229.         return self.things.pop(thing)

  230.     def check_exits(self):
  231.         print('You can exit to:')
  232.         for exit in self.exits:
  233.             print('   ', exit)

  234.     def add_exits(self, places):
  235.         for place in places:
  236.             self.exits[place.name] = (place, place.description)
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-13 11:47:07 | 只看该作者
全局:
lab06 extra代码是单独的不知道为什么...
回复

使用道具 举报

🔗
 楼主| lilirr 2019-8-13 11:47:55 | 只看该作者
全局:
单独测试会报错 但其实代码没有问题
我觉得应该是lab06.zip文件没有更新...

lab06_extra
  1. def vending_machine(snacks):
  2.     """Cycles through sequence of snacks.

  3.     >>> vender = vending_machine(('chips', 'chocolate', 'popcorn'))
  4.     >>> vender()
  5.     'chips'
  6.     >>> vender()
  7.     'chocolate'
  8.     >>> vender()
  9.     'popcorn'
  10.     >>> vender()
  11.     'chips'
  12.     >>> other = vending_machine(('brownie',))
  13.     >>> other()
  14.     'brownie'
  15.     >>> vender()
  16.     'chocolate'
  17.     """
  18.     "*** YOUR CODE HERE ***"
  19.     snacks = list(snacks)
  20.     cyc_index = -1
  21.     count = 0
  22.     def cycling():
  23.         nonlocal cyc_index,count
  24.         if count >=3:
  25.             cyc_index -= 3
  26.             count -=3
  27.         cyc_index +=1
  28.         count +=1
  29.         return snacks[cyc_index]        
  30.     return cycling
复制代码
回复

使用道具 举报

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

本版积分规则

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