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

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

 
全局:
公开课
学校名称: UCB
Unit号: 25
开课时间: 18sp
课程全名: CS 61A: Structure and Interpretation of Computer Programs
平台: 其他
URL: http://inst.eecs.berkeley.edu/~cs61a/sp18/

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
我在刷课的过程中有些地方卡壳了,就想着在网上搜一下答案
内容最全的github上sadly发现很多错误
就想着自己把已经校正了的答案合集发上来,供以后的小伙伴们参考
另一个帖子记录进度的我会把lj放在下一楼

评分

参与人数 7大米 +8 收起 理由
Gravel + 1 给你点个赞!
lillian0303 + 1 nb
喝来喝去可乐 + 2 给你点个赞!
hopestarta + 1 赞一个
smoothiethu + 1 很有用的信息!

查看全部评分


上一篇:每天打卡写2014 61b作业
下一篇:计算机系新生到来,请多多关照~
推荐
 楼主| lilirr 2019-7-16 11:39:54 | 只看该作者
全局:
RayHL 发表于 2019-7-16 06:13
请问楼主每次使用ok test之后都要我登陆账号,有解决方法嘛

在最后加--local
回复

使用道具 举报

推荐
 楼主| lilirr 2019-7-15 11:01:52 | 只看该作者
全局:
暂时就写到这里 之后会继续更新der
希望对大噶有用!
回复

使用道具 举报

推荐
 楼主| lilirr 2019-7-15 10:55:23 | 只看该作者
全局:
hw02

  1. HW_SOURCE_FILE = 'hw02.py'

  2. def square(x):
  3.     return x * x

  4. def identity(x):
  5.     return x

  6. triple = lambda x: 3 * x

  7. increment = lambda x: x + 1

  8. add = lambda x, y: x + y

  9. mul = lambda x, y: x * y

  10. def product(n, term):
  11.     """Return the product of the first n terms in a sequence.
  12.     n    -- a positive integer
  13.     term -- a function that takes one argument

  14.     >>> product(3, identity)  # 1 * 2 * 3
  15.     6
  16.     >>> product(5, identity)  # 1 * 2 * 3 * 4 * 5
  17.     120
  18.     >>> product(3, square)    # 1^2 * 2^2 * 3^2
  19.     36
  20.     >>> product(5, square)    # 1^2 * 2^2 * 3^2 * 4^2 * 5^2
  21.     14400
  22.     >>> product(3, increment) # (1+1) * (2+1) * (3+1)
  23.     24
  24.     >>> product(3, triple)    # 1*3 * 2*3 * 3*3
  25.     162
  26.     """
  27.     count = 1
  28.     pro = 1
  29.     while count <= n:
  30.         pro *= term(count)
  31.         count += 1
  32.     return pro

  33. # The identity function, defined using a lambda expression!
  34. identity = lambda k: k

  35. def factorial(n):
  36.     """Return n factorial for n >= 0 by calling product.

  37.     >>> factorial(4)
  38.     24
  39.     >>> factorial(6)
  40.     720
  41.     >>> from construct_check import check
  42.     >>> check(HW_SOURCE_FILE, 'factorial', ['Recursion', 'For', 'While'])
  43.     True
  44.     """
  45.     return product(n,identity)

  46. def make_adder(n):
  47.     """Return a function that takes an argument K and returns N + K.

  48.     >>> add_three = make_adder(3)
  49.     >>> add_three(1) + add_three(2)
  50.     9
  51.     >>> make_adder(1)(2)
  52.     3
  53.     """
  54.     def add_k(k):
  55.         return n + k
  56.     return add_k
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 10:53:13 | 只看该作者
全局:
另一个记录进度的帖子在这里https://www.1point3acres.com/bbs/thread-533071-1-1.html
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 10:54:01 | 只看该作者
全局:
hw01
  1. from operator import add, sub

  2. def a_plus_abs_b(a, b):
  3.     """Return a+abs(b), but without calling abs.

  4.     >>> a_plus_abs_b(2, 3)
  5.     5
  6.     >>> a_plus_abs_b(2, -3)
  7.     5
  8.     """
  9.     if b < 0:
  10.         f = sub
  11.     else:
  12.         f = add
  13.     return f(a, b)
  14. '''f应该是功能名'''

  15. def two_of_three(a, b, c):
  16.     """Return x*x + y*y, where x and y are the two largest members of the
  17.     positive numbers a, b, and c.

  18.     >>> two_of_three(1, 2, 3)
  19.     13
  20.     >>> two_of_three(5, 3, 1)
  21.     34
  22.     >>> two_of_three(10, 2, 8)
  23.     164
  24.     >>> two_of_three(5, 5, 5)
  25.     50
  26.     """
  27.     return max(a*a+b*b, b*b+c*c, a*a+c*c)

  28. def largest_factor(n):
  29.     """Return the largest factor of n that is smaller than n.

  30.     >>> largest_factor(15) # factors are 1, 3, 5
  31.     5
  32.     >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
  33.     40
  34.     >>> largest_factor(13) # factor is 1 since 13 is prime
  35.     1
  36.     """
  37.     """
  38. def largest_factor(n):
  39.     fac = 2
  40.     b = n%fac
  41.     while b!= 0:
  42.         fac = fac + 1
  43.         b = n%fac
  44.     if fac != n:
  45.         return int(n/fac)
  46.     else:
  47.         return 1

  48. """

  49. def if_function(condition, true_result, false_result):
  50.     """Return true_result if condition is a true value, and
  51.     false_result otherwise.

  52.     >>> if_function(True, 2, 3)
  53.     2
  54.     >>> if_function(False, 2, 3)
  55.     3
  56.     >>> if_function(3==2, 3+2, 3-2)
  57.     1
  58.     >>> if_function(3>2, 3+2, 3-2)
  59.     5
  60.     """
  61. '''
  62.     if condition:
  63.         return true_result
  64.     else:
  65.         return false_result
  66. '''

  67. def with_if_statement():
  68.     """
  69.     >>> with_if_statement()
  70.     1
  71.     """
  72.     if c():
  73.         return t()
  74.     else:
  75.         return f()

  76. def with_if_function():
  77.     return if_function(c(), t(), f())

  78. def c():
  79.     "*** YOUR CODE HERE ***"

  80. def t():
  81.     "*** YOUR CODE HERE ***"

  82. def f():
  83.     "*** YOUR CODE HERE ***"

  84. def hailstone(n):
  85.     """Print the hailstone sequence starting at n and return its
  86.     length.

  87.     >>> a = hailstone(10)
  88.     10
  89.     5
  90.     16
  91.     8
  92.     4
  93.     2
  94.     1
  95.     >>> a
  96.     7
  97.     """
  98. '''
  99.     def hailstone(n):
  100.     a = 1
  101.     print(n)
  102.     while n!= 1:
  103.         if n%2 == 0:
  104.             n = n/2
  105.             a = a+1
  106.             print(int(n))
  107.         else:
  108.             n = n*3 +1
  109.             a = a+1
  110.             print(int(n))
  111.     return a

  112. '''
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 10:58:15 | 只看该作者
全局:
hog proj

  1. """CS 61A Presents The Game of Hog."""

  2. from dice import six_sided, four_sided, make_test_dice
  3. from ucb import main, trace, interact

  4. GOAL_SCORE = 100  # The goal of Hog is to score 100 points.

  5. ######################
  6. # Phase 1: Simulator #
  7. ######################


  8. def roll_dice(num_rolls, dice=six_sided):
  9.     """Simulate rolling the DICE exactly NUM_ROLLS > 0 times. Return the sum of
  10.     the outcomes unless any of the outcomes is 1. In that case, return 1.

  11.     num_rolls:  The number of dice rolls that will be made.
  12.     dice:       A function that simulates a single dice roll outcome.
  13.     """
  14.     # These assert statements ensure that num_rolls is a positive integer.
  15.     assert type(num_rolls) == int, 'num_rolls must be an integer.'
  16.     assert num_rolls > 0, 'Must roll at least once.'
  17.     # BEGIN PROBLEM 1
  18.     n = 1
  19.     sum = 0
  20.     one_occur = 0#出现之前必须定义一下
  21.     while n <= num_rolls:
  22.         a = dice()
  23.         if a == 1:
  24.             one_occur = 1#用这个来标记1是否出现
  25.             sum = sum + a
  26.         else:
  27.             sum = sum + a
  28.         n += 1
  29.     if one_occur == 1:
  30.         return 1
  31.     else:
  32.         return sum
  33.     # END PROBLEM 1


  34. def free_bacon(score):
  35.     """Return the points scored from rolling 0 dice (Free Bacon).

  36.     score:  The opponent's current score.
  37.     """
  38.     assert score < 100, 'The game should be over.'
  39.     # BEGIN PROBLEM 2
  40.     tens = score//10
  41.     ones = score%10
  42.     if tens < ones:
  43.         return 2 + ones - tens
  44.     else:
  45.         return 2 + tens - ones
  46.     # END PROBLEM 2


  47. def take_turn(num_rolls, opponent_score, dice=six_sided):
  48.     """Simulate a turn rolling NUM_ROLLS dice, which may be 0 (Free Bacon).
  49.     Return the points scored for the turn by the current player.

  50.     num_rolls:       The number of dice rolls that will be made.
  51.     opponent_score:  The total score of the opponent.
  52.     dice:            A function that simulates a single dice roll outcome.
  53.     """
  54.     # Leave these assert statements here; they help check for errors.
  55.     assert type(num_rolls) == int, 'num_rolls must be an integer.'
  56.     assert num_rolls >= 0, 'Cannot roll a negative number of dice in take_turn.'
  57.     assert num_rolls <= 10, 'Cannot roll more than 10 dice.'
  58.     assert opponent_score < 100, 'The game should be over.'
  59.     # BEGIN PROBLEM 3
  60.     if num_rolls == 0:
  61.         return free_bacon(opponent_score)
  62.     else:
  63.         return roll_dice(num_rolls,dice) #参数有默认值的也是需要传递的,否则更改不了
  64.     # END PROBLEM 3


  65. def is_swap(score0, score1):
  66.     """Return whether one of the scores is an integer multiple of the other."""
  67.     # BEGIN PROBLEM 4
  68.     if (score0 > 1) and (score1 > 1):
  69.         if (score0 % score1 == 0) or (score1 % score0 == 0):
  70.             return True
  71.         else:
  72.             return False
  73.     else:
  74.         return False
  75.     # END PROBLEM 4


  76. def other(player):
  77.     """Return the other player, for a player PLAYER numbered 0 or 1.

  78.     >>> other(0)
  79.     1
  80.     >>> other(1)
  81.     0
  82.     """
  83.     return 1 - player


  84. def silence(score0, score1):
  85.     """Announce nothing (see Phase 2)."""
  86.     return silence


  87. def play(strategy0, strategy1, score0=0, score1=0, dice=six_sided,
  88.          goal=GOAL_SCORE, say=silence):
  89.     """Simulate a game and return the final scores of both players, with Player
  90.     0's score first, and Player 1's score second.

  91.     A strategy is a function that takes two total scores as arguments (the
  92.     current player's score, and the opponent's score), and returns a number of
  93.     dice that the current player wieu ron this turn.

  94.     strategy0:  The strategy function for Player 0, who plays first.
  95.     strategy1:  The strategy function for Player 1, who plays second.
  96.     score0:     Starting score for Player 0
  97.     score1:     Starting score for Player 1
  98.     dice:       A function of zero arguments that simulates a dice roll.
  99.     goal:       The game ends and someone wins when this score is reached.
  100.     say:        The commentary function to call at the end of the first turn.
  101.     """
  102.     player = 0  # Which player is about to take a turn, 0 (first) or 1 (second)
  103.     # BEGIN PROBLEM 5
  104.     while (score0 <goal) and (score1 <goal):#应该同时满足
  105.         if not player:#当第一位选手玩的时候
  106.             num_rolls = strategy0(score0, score1) #strategy0返回0号选手想要扔骰子的次数,这个时候直接调用就行,不用管细节,ph3才管
  107.             score0 += take_turn(num_rolls, score1, dice) #score0应该是累积的
  108.         else:
  109.             num_rolls = strategy1(score1,score0)
  110.             score1 += take_turn(num_rolls, score0, dice)
  111.         if is_swap(score0, score1): #第二个判断 和次序没有关系,只要满足互为因数就交换
  112.             score0, score1 = score1, score0
  113.         player = other(player)
  114.          # END PROBLEM 5
  115.         say = say(score0,score1)#这个格式适合say返回一个功能,需要对这个不停赋值的
  116.     return score0, score1


  117. #######################
  118. # Phase 2: Commentary #
  119. #######################


  120. def say_scores(score0, score1):
  121.     """A commentary function that announces the score for each player."""
  122.     print("Player 0 now has", score0, "and Player 1 now has", score1)
  123.     return say_scores

  124. def announce_lead_changes(previous_leader=None):
  125.     """Return a commentary function that announces lead changes.

  126.     >>> f0 = announce_lead_changes()
  127.     >>> f1 = f0(5, 0)
  128.     Player 0 takes the lead by 5
  129.     >>> f2 = f1(5, 12)
  130.     Player 1 takes the lead by 7
  131.     >>> f3 = f2(8, 12)
  132.     >>> f4 = f3(8, 13)
  133.     >>> f5 = f4(15, 13)
  134.     Player 0 takes the lead by 2
  135.     """
  136.     def say(score0, score1):
  137.         if score0 > score1:
  138.             leader = 0
  139.         elif score1 > score0:
  140.             leader = 1
  141.         else:
  142.             leader = None
  143.         if leader != None and leader != previous_leader:
  144.             print('Player', leader, 'takes the lead by', abs(score0 - score1))
  145.         return announce_lead_changes(leader)
  146.     return say

  147. def both(f, g):
  148.     """Return a commentary function that says what f says, then what g says.

  149.     >>> h0  = both(say_scores, announce_lead_changes())
  150.     >>> h1 = h0(10, 0)
  151.     Player 0 now has 10 and Player 1 now has 0
  152.     Player 0 takes the lead by 10
  153.     >>> h2 = h1(10, 6)
  154.     Player 0 now has 10 and Player 1 now has 6
  155.     >>> h3 = h2(6, 18) # Player 0 gets 8 points, then Swine Swap applies
  156.     Player 0 now has 6 and Player 1 now has 18
  157.     Player 1 takes the lead by 12
  158.     """
  159.     def say(score0, score1):
  160.         return both(f(score0, score1), g(score0, score1))
  161.     return say


  162. def announce_highest(who, previous_high=0, previous_score=0):
  163.     """Return a commentary function that announces when WHO's score
  164.     increases by more than ever before in the game.

  165.     >>> f0 = announce_highest(1) # Only announce Player 1 score gains
  166.     >>> f1 = f0(11, 0)
  167.     >>> f2 = f1(11, 1)
  168.     1 point! That's the biggest gain yet for Player 1
  169.     >>> f3 = f2(20, 1)
  170.     >>> f4 = f3(5, 20) # Player 1 gets 4 points, then Swine Swap applies
  171.     19 points! That's the biggest gain yet for Player 1
  172.     >>> f5 = f4(20, 40) # Player 0 gets 35 points, then Swine Swap applies
  173.     20 points! That's the biggest gain yet for Player 1
  174.     >>> f6 = f5(20, 55) # Player 1 gets 15 points; not enough for a new high
  175.     """
  176.     assert who == 0 or who == 1, 'The who argument should indicate a player.'
  177.     # BEGIN PROBLEM 7
  178.     assert who == 0 or who == 1, 'The who argument should indicate a player.'
  179.     # BEGIN PROBLEM 7
  180.     def commentary_score(score0, score1):
  181.         if not who:
  182.             now_score = score0
  183.         else:
  184.             now_score = score1
  185.         #pre_high/score在右边不会在这个frame里创造变量,在左边会创造和上一个frame里的pre_high冲突导致无法read data
  186.         score_dif = now_score - previous_score
  187.         if score_dif > previous_high:#pre_high记录最大差值,只有新最大差值出现才打印,而非出现新最大值打印
  188.             if now_score - previous_score < 2:
  189.                 print(score_dif,'point! That\'s the biggest gain yet for Player', who)
  190.             else:
  191.                 print(score_dif,'points! That\'s the biggest gain yet for Player', who)
  192.             return announce_highest(who,score_dif, now_score)
  193.         else:
  194.             return announce_highest(who,previous_high, now_score)
  195.     return commentary_score
  196.     # END PROBLEM 7


  197. #######################
  198. # Phase 3: Strategies #
  199. #######################


  200. def always_roll(n):
  201.     """Return a strategy that always rolls N dice.

  202.     A strategy is a function that takes two total scores as arguments (the
  203.     current player's score, and the opponent's score), and returns a number of
  204.     dice that the current player will roll this turn.

  205.     >>> strategy = always_roll(5)
  206.     >>> strategy(0, 0)
  207.     5
  208.     >>> strategy(99, 99)
  209.     5
  210.     """
  211.     def strategy(score, opponent_score):
  212.         return n
  213.     return strategy


  214. def make_averaged(fn, num_samples=1000):
  215.     """Return a function that returns the average value of FN when called.

  216.     To implement this function, you will have to use *args syntax, a new Python
  217.     feature introduced in this project.  See the project description.

  218.     >>> dice = make_test_dice(4, 2, 5, 1)
  219.     >>> averaged_dice = make_averaged(dice, 1000)
  220.     >>> averaged_dice()
  221.     3.0
  222.     """
  223.     # BEGIN PROBLEM 8
  224.     def ret_average(*arg):
  225.         n = 0
  226.         sum = 0
  227.         while n< num_samples:
  228.             sum += fn(*arg)
  229.             n +=1
  230.         return sum/num_samples
  231.     return ret_average
  232.     # END PROBLEM 8


  233. def max_scoring_num_rolls(dice=six_sided, num_samples=1000):
  234.     """Return the number of dice (1 to 10) that gives the highest average turn
  235.     score by calling roll_dice with the provided DICE over NUM_SAMPLES times.
  236.     Assume that the dice always return positive outcomes.

  237.     >>> dice = make_test_dice(1, 6)
  238.     >>> max_scoring_num_rolls(dice)
  239.     1
  240.     """
  241.     # BEGIN PROBLEM 9
  242.     n = 1
  243.     max_ave = 0
  244.     while n<=10:
  245.         now_ave = make_averaged(roll_dice)
  246.         if now_ave(n,dice) > max_ave:
  247.             max_ave = now_ave(n,dice)
  248.             max_roll = n
  249.         n += 1
  250.     return max_roll   
  251.     # END PROBLEM 9


  252. def winner(strategy0, strategy1):
  253.     """Return 0 if strategy0 wins against strategy1, and 1 otherwise."""
  254.     score0, score1 = play(strategy0, strategy1)
  255.     if score0 > score1:
  256.         return 0
  257.     else:
  258.         return 1


  259. def average_win_rate(strategy, baseline=always_roll(4)):
  260.     """Return the average win rate of STRATEGY against BASELINE. Averages the
  261.     winrate when starting the game as player 0 and as player 1.
  262.     """
  263.     win_rate_as_player_0 = 1 - make_averaged(winner)(strategy, baseline)
  264.     win_rate_as_player_1 = make_averaged(winner)(baseline, strategy)

  265.     return (win_rate_as_player_0 + win_rate_as_player_1) / 2


  266. def run_experiments():
  267.     """Run a series of strategy experiments and report results."""
  268.     if True:  # Change to False when done finding max_scoring_num_rolls
  269.         six_sided_max = max_scoring_num_rolls(six_sided)
  270.         print('Max scoring num rolls for six-sided dice:', six_sided_max)

  271.     if False:  # Change to True to test always_roll(8)
  272.         print('always_roll(8) win rate:', average_win_rate(always_roll(8)))

  273.     if False:  # Change to True to test bacon_strategy
  274.         print('bacon_strategy win rate:', average_win_rate(bacon_strategy))

  275.     if False:  # Change to True to test swap_strategy
  276.         print('swap_strategy win rate:', average_win_rate(swap_strategy))

  277.     if False:  # Change to True to test final_strategy
  278.         print('final_strategy win rate:', average_win_rate(final_strategy))

  279.     "*** You may add additional experiments as you wish ***"


  280. def bacon_strategy(score, opponent_score, margin=8, num_rolls=4):
  281.     """This strategy rolls 0 dice if that gives at least MARGIN points, and
  282.     rolls NUM_ROLLS otherwise.
  283.     """
  284.     # BEGIN PROBLEM 10
  285.     if free_bacon(opponent_score) >= margin:
  286.         return 0
  287.     else:
  288.         return num_rolls
  289.     # END PROBLEM 10


  290. def swap_strategy(score, opponent_score, margin=8, num_rolls=4):
  291.     """This strategy rolls 0 dice when it triggers a beneficial swap. It also
  292.     rolls 0 dice if it gives at least MARGIN points. Otherwise, it rolls
  293.     NUM_ROLLS.
  294.     """
  295.     # BEGIN PROBLEM 11
  296.     if is_swap(score,opponent_score):
  297.         if score < opponent_score:
  298.             return 0
  299.         else:
  300.             return num_rolls
  301.     elif free_bacon(opponent_score) >= margin:
  302.         return 0
  303.     else:
  304.         return num_rolls
  305.     # END PROBLEM 11


  306. def final_strategy(score, opponent_score):
  307.     """Write a brief description of your final strategy.

  308.     *** YOUR DESCRIPTION HERE ***
  309.     """
  310.     # BEGIN PROBLEM 12
  311.     return 4  # Replace this statement
  312.     # END PROBLEM 12


  313. ##########################
  314. # Command Line Interface #
  315. ##########################

  316. # NOTE: Functions in this section do not need to be changed. They use features
  317. # of Python not yet covered in the course.


  318. @main
  319. def run(*args):
  320.     """Read in the command-line argument and calls corresponding functions.

  321.     This function uses Python syntax/techniques not yet covered in this course.
  322.     """
  323.     import argparse
  324.     parser = argparse.ArgumentParser(description="Play Hog")
  325.     parser.add_argument('--run_experiments', '-r', action='store_true',
  326.                         help='Runs strategy experiments')

  327.     args = parser.parse_args()

  328.     if args.run_experiments:
  329.         run_experiments()
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 10:59:05 | 只看该作者
全局:
hw03

  1. HW_SOURCE_FILE = 'hw03.py'

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

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

  7.     >>> has_seven(3)
  8.     False
  9.     >>> has_seven(7)
  10.     True
  11.     >>> has_seven(2734)
  12.     True
  13.     >>> has_seven(2634)
  14.     False
  15.     >>> has_seven(734)
  16.     True
  17.     >>> has_seven(7777)
  18.     True
  19.     >>> from construct_check import check
  20.     >>> check(HW_SOURCE_FILE, 'has_seven',
  21.     ...       ['Assign', 'AugAssign'])
  22.     True
  23.     """
  24.     "*** YOUR CODE HERE ***"
  25.     if k<10:
  26.         return k%10 ==7
  27.     else:HW_SOURCE_FILE = 'hw03.py'

  28. #############
  29. # Questions #
  30. #############

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

  33.     >>> has_seven(3)
  34.     False
  35.     >>> has_seven(7)
  36.     True
  37.     >>> has_seven(2734)
  38.     True
  39.     >>> has_seven(2634)
  40.     False
  41.     >>> has_seven(734)
  42.     True
  43.     >>> has_seven(7777)
  44.     True
  45.     >>> from construct_check import check
  46.     >>> check(HW_SOURCE_FILE, 'has_seven',
  47.     ...       ['Assign', 'AugAssign'])
  48.     True
  49.     """
  50.     "*** YOUR CODE HERE ***"
  51.     if k<10:
  52.         return k%10 ==7
  53.     else:
  54.         return k%10 == 7 or has_seven(k//10)
  55.         
  56. def summation(n, term):

  57.     """Return the sum of the first n terms in the sequence defined by term.
  58.     Implement using recursion!

  59.     >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
  60.     225
  61.     >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
  62.     54
  63.     >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
  64.     62
  65.     >>> # Do not use while/for loops!
  66.     >>> from construct_check import check
  67.     >>> check(HW_SOURCE_FILE, 'summation',
  68.     ...       ['While', 'For'])
  69.     True
  70.     """
  71.     assert n >= 1
  72.     "*** YOUR CODE HERE ***"
  73.     if n ==1:
  74.         return term (1) #base case
  75.     else:
  76.         return term(n)+summation(n-1,term)


  77.    
  78. def square(x):
  79.     return x * x

  80. def identity(x):
  81.     return x

  82. triple = lambda x: 3 * x

  83. increment = lambda x: x + 1

  84. add = lambda x, y: x + y

  85. mul = lambda x, y: x * y

  86. def accumulate(combiner, base, n, term):
  87.     """Return the result of combining the first n terms in a sequence and base.
  88.     The terms to be combined are term(1), term(2), ..., term(n).  combiner is a
  89.     two-argument commutative function.

  90.     >>> accumulate(add, 0, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
  91.     15
  92.     >>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
  93.     26
  94.     >>> accumulate(add, 11, 0, identity) # 11
  95.     11
  96.     >>> accumulate(add, 11, 3, square)   # 11 + 1^2 + 2^2 + 3^2
  97.     25
  98.     >>> accumulate(mul, 2, 3, square)   # 2 * 1^2 * 2^2 * 3^2
  99.     72
  100.     """
  101.     "*** YOUR CODE HERE ***"
  102.     if n == 0:
  103.         return base
  104.     else:
  105.         return combiner(term(n),accumulate(combiner,base,n-1,term)) #一定要一个代表n情况的表达式和之后的循环
  106.         #除了tree recursion一般很少两个base case的,所以当写了两个bc看能不能合并否则可能报错
  107.    
  108. def summation_using_accumulate(n, term):
  109.     """Returns the sum of term(1) + ... + term(n). The implementation
  110.     uses accumulate.

  111.     >>> summation_using_accumulate(5, square)
  112.     55
  113.     >>> summation_using_accumulate(5, triple)
  114.     45
  115.     >>> from construct_check import check
  116.     >>> check(HW_SOURCE_FILE, 'summation_using_accumulate',
  117.     ...       ['Recursion', 'For', 'While'])
  118.     True
  119.     """
  120.     "*** YOUR CODE HERE ***"

  121.     return accumulate(add,0,n,term)

  122. def product_using_accumulate(n, term):
  123.     """An implementation of product using accumulate.

  124.     >>> product_using_accumulate(4, square)
  125.     576
  126.     >>> product_using_accumulate(6, triple)
  127.     524880
  128.     >>> from construct_check import check
  129.     >>> check(HW_SOURCE_FILE, 'product_using_accumulate',
  130.     ...       ['Recursion', 'For', 'While'])
  131.     True
  132.     """
  133.     "*** YOUR CODE HERE ***"
  134.     return accumulate(mul,1,n,term)

  135. def filtered_accumulate(combiner, base, pred, n, term):
  136.     """Return the result of combining the terms in a sequence of N terms
  137.     that satisfy the predicate pred. combiner is a two-argument function.
  138.     If v1, v2, ..., vk are the values in term(1), term(2), ..., term(N)
  139.     that satisfy pred, then the result is
  140.          base combiner v1 combiner v2 ... combiner vk
  141.     (treating combiner as if it were a binary operator, like +). The
  142.     implementation uses accumulate.

  143.     >>> filtered_accumulate(add, 0, lambda x: True, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
  144.     15
  145.     >>> filtered_accumulate(add, 11, lambda x: False, 5, identity) # 11
  146.     11
  147.     >>> filtered_accumulate(add, 0, odd, 5, identity)   # 0 + 1 + 3 + 5
  148.     9
  149.     >>> filtered_accumulate(mul, 1, greater_than_5, 5, square)  # 1 * 9 * 16 * 25
  150.     3600
  151.     >>> # Do not use while/for loops or recursion
  152.     >>> from construct_check import check
  153.     >>> check(HW_SOURCE_FILE, 'filtered_accumulate',
  154.     ...       ['While', 'For', 'Recursion'])
  155.     True
  156.     """
  157.     def combine_if(x, y):
  158.         "*** YOUR CODE HERE ***"
  159.         if pred(x):
  160.             return combiner(x,y)
  161.         else:
  162.             return y
  163.     return accumulate(combine_if, base, n, term)

  164. def odd(x):
  165.     return x % 2 == 1

  166. def greater_than_5(x):
  167.     return x > 5

  168. def make_repeater(f, n):
  169.     """Return the function that computes the nth application of f.

  170.     >>> add_three = make_repeater(increment, 3)
  171.     >>> add_three(5)
  172.     8
  173.     >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
  174.     243
  175.     >>> make_repeater(square, 2)(5) # square(square(5))
  176.     625
  177.     >>> make_repeater(square, 4)(5) # square(square(square(square(5))))
  178.     152587890625
  179.     >>> make_repeater(square, 0)(5)
  180.     5
  181.     """
  182.     "*** YOUR CODE HERE ***"
  183.     '''第一个解法'''
  184.     '''if n == 0:
  185.         return identity
  186.     elif n ==1:
  187.         return f
  188.     else:
  189.         a = f
  190.         i = 1
  191.         while i < n:
  192.             a = compose1(a,f)
  193.             i = i+1
  194.         return a'''
  195.     '''第二个解法'''
  196.     return accumulate(compose1,lambda x: x,n,lambda x:f)#注意一定是lambdax:f,如果只是f在term(n)即f(n)的时候返回的一个int 返回的f而非f(x)说明x对f没有作用,即n对increment等函数没有影响,返回的只是一个函数而已

  197. def compose1(f, g):
  198.     """Return a function h, such that h(x) = f(g(x))."""
  199.     def h(x):
  200.         return f(g(x))
  201.     return h

  202. ###################
  203. # Extra Questions #
  204. ###################

  205. quine = """
  206. "*** YOUR CODE HERE ***"
  207. """

  208. def zero(f):
  209.     return lambda x: x

  210. def successor(n):
  211.     return lambda f: lambda x: f(n(f)(x))

  212. def one(f):
  213.     """Church numeral 1: same as successor(zero)"""
  214.     "*** YOUR CODE HERE ***"

  215. def two(f):
  216.     """Church numeral 2: same as successor(successor(zero))"""
  217.     "*** YOUR CODE HERE ***"

  218. three = successor(two)

  219. def church_to_int(n):
  220.     """Convert the Church numeral n to a Python integer.

  221.     >>> church_to_int(zero)
  222.     0
  223.     >>> church_to_int(one)
  224.     1
  225.     >>> church_to_int(two)
  226.     2
  227.     >>> church_to_int(three)
  228.     3
  229.     """
  230.     "*** YOUR CODE HERE ***"

  231. def add_church(m, n):
  232.     """Return the Church numeral for m + n, for Church numerals m and n.

  233.     >>> church_to_int(add_church(two, three))
  234.     5
  235.     """
  236.     "*** YOUR CODE HERE ***"

  237. def mul_church(m, n):
  238.     """Return the Church numeral for m * n, for Church numerals m and n.

  239.     >>> four = successor(three)
  240.     >>> church_to_int(mul_church(two, three))
  241.     6
  242.     >>> church_to_int(mul_church(three, four))
  243.     12
  244.     """
  245.     "*** YOUR CODE HERE ***"

  246. def pow_church(m, n):
  247.     """Return the Church numeral m ** n, for Church numerals m and n.

  248.     >>> church_to_int(pow_church(two, three))
  249.     8
  250.     >>> church_to_int(pow_church(three, two))
  251.     9
  252.     """
  253.     "*** YOUR CODE HERE ***"

  254.     return k%10 == 7 or has_seven(k//10)
  255.         
  256. def summation(n, term):

  257.     """Return the sum of the first n terms in the sequence defined by term.
  258.     Implement using recursion!

  259.     >>> summation(5, lambda x: x * x * x) # 1^3 + 2^3 + 3^3 + 4^3 + 5^3
  260.     225
  261.     >>> summation(9, lambda x: x + 1) # 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
  262.     54
  263.     >>> summation(5, lambda x: 2**x) # 2^1 + 2^2 + 2^3 + 2^4 + 2^5
  264.     62
  265.     >>> # Do not use while/for loops!
  266.     >>> from construct_check import check
  267.     >>> check(HW_SOURCE_FILE, 'summation',
  268.     ...       ['While', 'For'])
  269.     True
  270.     """
  271.     assert n >= 1
  272.     "*** YOUR CODE HERE ***"
  273.     if n ==1:
  274.         return term (1) #base case
  275.     else:
  276.         return term(n)+summation(n-1,term)


  277.    
  278. def square(x):
  279.     return x * x

  280. def identity(x):
  281.     return x

  282. triple = lambda x: 3 * x

  283. increment = lambda x: x + 1

  284. add = lambda x, y: x + y

  285. mul = lambda x, y: x * y

  286. def accumulate(combiner, base, n, term):
  287.     """Return the result of combining the first n terms in a sequence and base.
  288.     The terms to be combined are term(1), term(2), ..., term(n).  combiner is a
  289.     two-argument commutative function.

  290.     >>> accumulate(add, 0, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
  291.     15
  292.     >>> accumulate(add, 11, 5, identity) # 11 + 1 + 2 + 3 + 4 + 5
  293.     26
  294.     >>> accumulate(add, 11, 0, identity) # 11
  295.     11
  296.     >>> accumulate(add, 11, 3, square)   # 11 + 1^2 + 2^2 + 3^2
  297.     25
  298.     >>> accumulate(mul, 2, 3, square)   # 2 * 1^2 * 2^2 * 3^2
  299.     72
  300.     """
  301.     "*** YOUR CODE HERE ***"
  302.     if n == 0:
  303.         return base
  304.     else:
  305.         return combiner(term(n),accumulate(combiner,base,n-1,term)) #一定要一个代表n情况的表达式和之后的循环
  306.         #除了tree recursion一般很少两个base case的,所以当写了两个bc看能不能合并否则可能报错
  307.    
  308. def summation_using_accumulate(n, term):
  309.     """Returns the sum of term(1) + ... + term(n). The implementation
  310.     uses accumulate.

  311.     >>> summation_using_accumulate(5, square)
  312.     55
  313.     >>> summation_using_accumulate(5, triple)
  314.     45
  315.     >>> from construct_check import check
  316.     >>> check(HW_SOURCE_FILE, 'summation_using_accumulate',
  317.     ...       ['Recursion', 'For', 'While'])
  318.     True
  319.     """
  320.     "*** YOUR CODE HERE ***"

  321.     return accumulate(add,0,n,term)

  322. def product_using_accumulate(n, term):
  323.     """An implementation of product using accumulate.

  324.     >>> product_using_accumulate(4, square)
  325.     576
  326.     >>> product_using_accumulate(6, triple)
  327.     524880
  328.     >>> from construct_check import check
  329.     >>> check(HW_SOURCE_FILE, 'product_using_accumulate',
  330.     ...       ['Recursion', 'For', 'While'])
  331.     True
  332.     """
  333.     "*** YOUR CODE HERE ***"
  334.     return accumulate(mul,1,n,term)

  335. def filtered_accumulate(combiner, base, pred, n, term):
  336.     """Return the result of combining the terms in a sequence of N terms
  337.     that satisfy the predicate pred. combiner is a two-argument function.
  338.     If v1, v2, ..., vk are the values in term(1), term(2), ..., term(N)
  339.     that satisfy pred, then the result is
  340.          base combiner v1 combiner v2 ... combiner vk
  341.     (treating combiner as if it were a binary operator, like +). The
  342.     implementation uses accumulate.

  343.     >>> filtered_accumulate(add, 0, lambda x: True, 5, identity)  # 0 + 1 + 2 + 3 + 4 + 5
  344.     15
  345.     >>> filtered_accumulate(add, 11, lambda x: False, 5, identity) # 11
  346.     11
  347.     >>> filtered_accumulate(add, 0, odd, 5, identity)   # 0 + 1 + 3 + 5
  348.     9
  349.     >>> filtered_accumulate(mul, 1, greater_than_5, 5, square)  # 1 * 9 * 16 * 25
  350.     3600
  351.     >>> # Do not use while/for loops or recursion
  352.     >>> from construct_check import check
  353.     >>> check(HW_SOURCE_FILE, 'filtered_accumulate',
  354.     ...       ['While', 'For', 'Recursion'])
  355.     True
  356.     """
  357.     def combine_if(x, y):
  358.         "*** YOUR CODE HERE ***"
  359.         if pred(x):
  360.             return combiner(x,y)
  361.         else:
  362.             return y
  363.     return accumulate(combine_if, base, n, term)

  364. def odd(x):
  365.     return x % 2 == 1

  366. def greater_than_5(x):
  367.     return x > 5

  368. def make_repeater(f, n):
  369.     """Return the function that computes the nth application of f.

  370.     >>> add_three = make_repeater(increment, 3)
  371.     >>> add_three(5)
  372.     8
  373.     >>> make_repeater(triple, 5)(1) # 3 * 3 * 3 * 3 * 3 * 1
  374.     243
  375.     >>> make_repeater(square, 2)(5) # square(square(5))
  376.     625
  377.     >>> make_repeater(square, 4)(5) # square(square(square(square(5))))
  378.     152587890625
  379.     >>> make_repeater(square, 0)(5)
  380.     5
  381.     """
  382.     "*** YOUR CODE HERE ***"
  383.     '''第一个解法'''
  384.     '''if n == 0:
  385.         return identity
  386.     elif n ==1:
  387.         return f
  388.     else:
  389.         a = f
  390.         i = 1
  391.         while i < n:
  392.             a = compose1(a,f)
  393.             i = i+1
  394.         return a'''
  395.     '''第二个解法'''
  396.     return accumulate(compose1,lambda x: x,n,lambda x:f)#注意一定是lambdax:f,如果只是f在term(n)即f(n)的时候返回的一个int 返回的f而非f(x)说明x对f没有作用,即n对increment等函数没有影响,返回的只是一个函数而已

  397. def compose1(f, g):
  398.     """Return a function h, such that h(x) = f(g(x))."""
  399.     def h(x):
  400.         return f(g(x))
  401.     return h

  402. ###################
  403. # Extra Questions #
  404. ###################

  405. quine = """
  406. "*** YOUR CODE HERE ***"
  407. """

  408. def zero(f):
  409.     return lambda x: x

  410. def successor(n):
  411.     return lambda f: lambda x: f(n(f)(x))

  412. def one(f):
  413.     """Church numeral 1: same as successor(zero)"""
  414.     "*** YOUR CODE HERE ***"

  415. def two(f):
  416.     """Church numeral 2: same as successor(successor(zero))"""
  417.     "*** YOUR CODE HERE ***"

  418. three = successor(two)

  419. def church_to_int(n):
  420.     """Convert the Church numeral n to a Python integer.

  421.     >>> church_to_int(zero)
  422.     0
  423.     >>> church_to_int(one)
  424.     1
  425.     >>> church_to_int(two)
  426.     2
  427.     >>> church_to_int(three)
  428.     3
  429.     """
  430.     "*** YOUR CODE HERE ***"

  431. def add_church(m, n):
  432.     """Return the Church numeral for m + n, for Church numerals m and n.

  433.     >>> church_to_int(add_church(two, three))
  434.     5
  435.     """
  436.     "*** YOUR CODE HERE ***"

  437. def mul_church(m, n):
  438.     """Return the Church numeral for m * n, for Church numerals m and n.

  439.     >>> four = successor(three)
  440.     >>> church_to_int(mul_church(two, three))
  441.     6
  442.     >>> church_to_int(mul_church(three, four))
  443.     12
  444.     """
  445.     "*** YOUR CODE HERE ***"

  446. def pow_church(m, n):
  447.     """Return the Church numeral m ** n, for Church numerals m and n.

  448.     >>> church_to_int(pow_church(two, three))
  449.     8
  450.     >>> church_to_int(pow_church(three, two))
  451.     9
  452.     """
  453.     "*** YOUR CODE HERE ***"
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 11:00:22 | 只看该作者
全局:
lab02

  1. """Lab 2: Lambda Expressions and Higher Order Functions"""

  2. # Lambda Functions

  3. def lambda_curry2(func):
  4.     """
  5.     Returns a Curried version of a two-argument function FUNC.
  6.     >>> from operator import add
  7.     >>> curried_add = lambda_curry2(add)
  8.     >>> add_three = curried_add(3)
  9.     >>> add_three(5)
  10.     8
  11.     """
  12.     def curry2(x):
  13.         def curry3(y):
  14.             return func(x,y)
  15.         return curry3
  16.     return curry2
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 11:01:26 | 只看该作者
全局:
lab02_extra

  1. """ Optional problems for lab02 """

  2. from lab02 import *

  3. # Higher Order Functions

  4. def compose1(f, g):
  5.     """Return the composition function which given x, computes f(g(x)).

  6.     >>> add_one = lambda x: x + 1        # adds one to x
  7.     >>> square = lambda x: x**2
  8.     >>> a1 = compose1(square, add_one)   # (x + 1)^2
  9.     >>> a1(4)
  10.     25
  11.     >>> mul_three = lambda x: x * 3      # multiplies 3 to x
  12.     >>> a2 = compose1(mul_three, a1)    # ((x + 1)^2) * 3
  13.     >>> a2(4)
  14.     75
  15.     >>> a2(5)
  16.     108
  17.     """
  18.     return lambda x: f(g(x))

  19. def composite_identity(f, g):
  20.     """
  21.     Return a function with one parameter x that returns True if f(g(x)) is
  22.     equal to g(f(x)). You can assume the result of g(x) is a valid input for f
  23.     and vice versa.

  24.     >>> add_one = lambda x: x + 1        # adds one to x
  25.     >>> square = lambda x: x**2
  26.     >>> b1 = composite_identity(square, add_one)
  27.     >>> b1(0)                            # (0 + 1)^2 == 0^2 + 1
  28.     True
  29.     >>> b1(4)                            # (4 + 1)^2 != 4^2 + 1
  30.     False
  31.     """
  32.     def is_true(x):
  33.         return compose1(f,g)(x) == compose1(g,f)(x)
  34.     return is_true

  35. def count_cond(condition):
  36.     """Returns a function with one parameter N that counts all the numbers from
  37.     1 to N that satisfy the two-argument predicate function CONDITION.

  38.     >>> count_factors = count_cond(lambda n, i: n % i == 0)
  39.     >>> count_factors(2)   # 1, 2
  40.     2
  41.     >>> count_factors(4)   # 1, 2, 4
  42.     3
  43.     >>> count_factors(12)  # 1, 2, 3, 4, 6, 12
  44.     6

  45.     >>> is_prime = lambda n, i: count_factors(i) == 2
  46.     >>> count_primes = count_cond(is_prime)
  47.     >>> count_primes(2)    # 2
  48.     1
  49.     >>> count_primes(3)    # 2, 3
  50.     2
  51.     >>> count_primes(4)    # 2, 3
  52.     2
  53.     >>> count_primes(5)    # 2, 3, 5
  54.     3
  55.     >>> count_primes(20)   # 2, 3, 5, 7, 11, 13, 17, 19
  56.     8
  57.     """
  58.     def count_num(n):
  59.         i, sum = 1, 0
  60.         while  i<= n:
  61.             if condition(n,i):
  62.                 sum +=1
  63.             i +=1
  64.         return sum
  65.     return count_num

  66. def cycle(f1, f2, f3):
  67.     """Returns a function that is itself a higher-order function.

  68.     >>> def add1(x):
  69.     ...     return x + 1
  70.     >>> def times2(x):
  71.     ...     return x * 2
  72.     >>> def add3(x):
  73.     ...     return x + 3
  74.     >>> my_cycle = cycle(add1, times2, add3)
  75.     >>> identity = my_cycle(0)
  76.     >>> identity(5)
  77.     5
  78.     >>> add_one_then_double = my_cycle(2)
  79.     >>> add_one_then_double(1)
  80.     4
  81.     >>> do_all_functions = my_cycle(3)
  82.     >>> do_all_functions(2)
  83.     9
  84.     >>> do_more_than_a_cycle = my_cycle(4)
  85.     >>> do_more_than_a_cycle(2)
  86.     10
  87.     >>> do_two_cycles = my_cycle(6)
  88.     >>> do_two_cycles(1)
  89.     19
  90.     """
  91.     "*** YOUR CODE HERE ***"
  92.     def take_arg_n(n):
  93.         def take_arg_x(x):
  94.             sum_res,i = x,0
  95.             ori_ls = [f1,f2,f3]
  96.             func_ls = ori_ls*(n//3) + ori_ls[0:n%3]
  97.             if n == 0:
  98.                 return x
  99.             else:
  100.                 while i<n:
  101.                     sum_res = func_ls[i](sum_res)
  102.                     i +=1
  103.                 return sum_res
  104.         return take_arg_x
  105.     return take_arg_n
复制代码
回复

使用道具 举报

🔗
 楼主| lilirr 2019-7-15 20:59:39 | 只看该作者
全局:
lab03

  1. """ Lab 3: Recursion and Midterm Review """

  2. def gcd(a, b):
  3.     """Returns the greatest common divisor of a and b.
  4.     Should be implemented using recursion.

  5.     >>> gcd(34, 19)
  6.     1
  7.     >>> gcd(39, 91)
  8.     13
  9.     >>> gcd(20, 30)
  10.     10
  11.     >>> gcd(40, 40)
  12.     40
  13.     """
  14.     "*** YOUR CODE HERE ***"
  15.     if a%b == 0 or b%a == 0:
  16.         return min(a,b)
  17.     else:
  18.         return gcd(b,a%b)

  19. def hailstone(n):
  20.     """Print out the hailstone sequence starting at n, and return the
  21.     number of elements in the sequence.

  22.     >>> a = hailstone(10)
  23.     10
  24.     5
  25.     16
  26.     8
  27.     4
  28.     2
  29.     1
  30.     >>> a
  31.     7
  32.     """
  33.     "*** YOUR CODE HERE ***"
  34.     print(n)
  35.     step = 1
  36.     while n!=1:
  37.         if n%2 == 0:
  38.             n = int(n/2)
  39.         else:
  40.             n = int(n*3+1)
  41.         print(n)
  42.         step +=1
  43.     return step
  44.             
复制代码
回复

使用道具 举报

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

本版积分规则

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