<p>您可以通过以下方式实现您想要实现的目标-</p>
<h2>正确的解决方案-</h2>
<pre><code>import random
heads = 0
tails = 0
toss = heads + tails
toss = int(input("How many coin tosses would you like to simulate?"))
max_head_streak,max_tail_streak,curr_head_streak,curr_tail_streak=0,0,0,0
while heads + tails < toss:
coin = random.randint(1, 2)
if coin == 1:
# If coin is 1, we increase count of head
heads = heads + 1
# Since the current one is head, we just increase current head streak and reset the tail streak
curr_head_streak += 1
curr_tail_streak = 0
else:
# if coin isn't 1, we increase count of tail
tails = tails + 1
# Similarly, We just increase current tail streak and reset head streak in this case
curr_tail_streak += 1
curr_head_streak = 0
# On each iteration, we set the max_head_streak and max_tail_streak as per below -
max_head_streak=max(max_head_streak,curr_head_streak)
max_tail_streak=max(max_tail_streak,curr_tail_streak)
print("The total amount of heads: ",heads)
print("The best streak of heads: ",max_head_streak)
print("The total amount of tails: ",tails)
print("The best streak of tails: ",max_tail_streak)
</code></pre>
<p><strong>输出:</strong></p>
<pre><code>How many coin tosses would you like to simulate?10
The total amount of heads: 6
The best streak of heads: 3
The total amount of tails: 4
The best streak of tails: 2
</code></pre>
<p><strong>哪里出了问题-</strong></p>
<blockquote>
<h3>Your code -</h3>
<pre><code>while heads + tails < toss:
coin = random.randint(1, 2)
if coin == 1:
toss += 1
heads = heads + 1
else:
coin == 2
toss += 1
tails = tails + 1
</code></pre>
</blockquote>
<p>您的代码将运行在一个无限循环中,因为循环永远不会脱离循环。您正在增加投掷计数以及头/尾计数。您只需要增加头/尾计数,而不需要增加投掷计数。其他更改可根据我的上述解决方案进行</p>