def announce_highest(who, last_score=0, running_high=0): """Return a commentary function that announces when WHO's score increases by more than ever before in the game.
NOTE: the following game is not possible under the rules, it's just an example for the sake of the doctest
>>> f0 = announce_highest(1) # Only announce Player 1 score gains >>> f1 = f0(12, 0) >>> f2 = f1(12, 9) 9 point(s)! The most yet for Player 1 >>> f3 = f2(20, 9) >>> f4 = f3(20, 30) 21 point(s)! The most yet for Player 1 >>> f5 = f4(20, 47) # Player 1 gets 17 points; not enough for a new high >>> f6 = f5(21, 47) >>> f7 = f6(21, 77) 30 point(s)! The most yet for Player 1 """ assert who == 0 or who == 1, 'The who argument should indicate a player.' # BEGIN PROBLEM 7 "*** YOUR CODE HERE ***" def say(new_score_0, new_score_1, last_running_high = running_high): if who == 0: new_score = new_score_0 new_running_high = new_score_0 - last_score else: new_score = new_score_1 new_running_high = new_score_1 - last_score
if new_running_high > last_running_high: last_running_high = new_running_high print(str(new_running_high),"point(s)! The most yet for Player " + str(who)) new_run_high = last_running_high return announce_highest(who, new_score, new_run_high) return say # END PROBLEM 7
def announce_highest(who, last_score=0, running_high=0): # BEGIN PROBLEM 7 "*** YOUR CODE HERE ***" def say(new_score_0, new_score_1, last_running_high = running_high): pass return say # END PROBLEM 7
可见,调用 announce_highest 的本质是获取到一个 say 函数,每次调用 say 函数,我们都期待它能检测是否要更新记录,而不断地更新最大幅度,则要不断地获取并调用 say 函数,那让 say 返回获取 say 函数的函数就解决了这个问题,即下面代码
plaintext
1 2 3 4 5 6 7 8 9 10 11 12
def announce_highest(who, last_score=0, running_high=0): # BEGIN PROBLEM 7 "*** YOUR CODE HERE ***" def say(new_score_0, new_score_1, last_running_high = running_high): pass
return announce_highest(who, new_score, new_run_high) return say # END PROBLEM 7
再看测试代码就清晰多了
>>> f0 = announce_highest(1) # Only announce Player 1 score gains 这里的 f0 实际上是 who 为 1 时的 say 函数
>>> f1 = f0(12, 0) f1 的本质是代入 new_score_0 = 12 和 new_score_1 = 0 的 say 函数执行后,返回的新的 say 函数。你问 announce_highest 去哪了?announce_highest 也返回的 say 函数,只是没有参数代入的 say 函数而已
其它测试语句以上述类推
后面在 geek for geek 进行了更深入的学习,发现此前在 LALC 用的迭代器就是高阶函数的运用