Still conduct their own hog project today.
Project output requirement is a maximum increment players.
I have written the following code:
def announce_highest(who, prev_high=0, prev_score=0):
assert who == 0 or who == 1, 'The who argument should indicate a player.'
def say0(score0, score1):
nonlocal prev_high
nonlocal prev_score
cur_gain = score0 - prev_score #求出当前分和前一轮分的增量
if cur_gain > prev_high:
print(str(cur_gain)+" point(s)! That's the biggest gain yet for Player 0")
prev_high = cur_gain
prev_score = score0
return announce_highest(who, prev_high, prev_score)
return say0
The results did not pass the test:
This test input is who = 1, i.e. each second value transfer
can see the final test f2_again = f1 (11, 9)
The purpose of this line of code is a fraction of a change, function still works, the output should be 9. But my code has no output.
In its own port to run a bit
to be output 5,7,6, 6 but does not output
the last line changed to f1 f0 output found 6
It can be learned, is a function of the inner frame misalignment.
On pythontutor run and found, and the value change prev_high prev_score which when executed h1 of the frame (i.e., prior to the code f1).
Here and expectations do not match, because want to say a read-only function, without changing the two local variables.
It is because h1 of the last call, and so prev_high = 5 prev_score = 12, when the next call, cur_gain -1, could not be output.
I realize I function
nonlocal prev_high
nonlocal prev_score
These two variables and variable binding within announce_highest, naturally led to launch a body.
The final one of my friends told me to set two new amount new_score, new_high, so that the internal read only say do not change, thereby solving the problem.
Internal running again f1 prev_high and prev_score still 5,5, insert the update can be achieved.
def announce_highest(who, prev_high=0, prev_score=0):
assert who == 0 or who == 1, 'The who argument should indicate a player.'
def say0(score0, score1):
cur_gain = score0 - prev_score
if cur_gain > prev_high:
print(str(cur_gain)+" point(s)! That's the biggest gain yet for Player 0")
new_high = cur_gain
new_score = score0
return announce_highest(who, new_high, new_score)
return say0
f0 = announce_highest(0)
f1 = f0(5,0)
f2 = f1(12,5)
f2_again = f1(11,9)