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. >>> f0 = announce_highest(1) # Only announce Player 1 score gains >>> f1 = f0(12, 0) >>> f2 = f1(12, 9) 9 point(s)! That's a record gain for Player 1! >>> f3 = f2(20, 9) >>> f4 = f3(20, 30) 21 point(s)! That's a record gain 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)! That's a record gain for Player 1! """ assert who == 0 or who == 1, 'The who argument should indicate a player.' # BEGIN PROBLEM 7 "*** YOUR CODE HERE ***" # END PROBLEM 7请完善这个函数
时间: 2023-12-18 17:03:59 浏览: 193
可以用闭包的方式实现这个函数,返回一个 commentary 函数,在每次调用时比较当前得分和之前的最高得分,如果超过了最高得分则输出提示信息。
```python
def announce_highest(who, last_score=0, running_high=0):
assert who == 0 or who == 1, 'The who argument should indicate a player.'
def commentary(score, high_score=running_high):
nonlocal last_score
nonlocal running_high
gain = score - last_score
last_score = score
if gain > high_score:
running_high = gain
print(f"{gain} point(s)! That's a record gain for Player {who}!")
return announce_highest(who, last_score, running_high)
return commentary
```
这里使用了 nonlocal 关键字来访问外部函数的变量,因为需要在每次调用 commentary 函数时更新 last_score 和 running_high 的值。同时,由于需要返回一个新的 commentary 函数,所以在最后一行调用了 announce_highest 函数,并传入当前的 last_score 和 running_high 值。
阅读全文