您可以通过以下方式完成您想要实现的目标 -
正确的解决方案 -
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)
输出:
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
你哪里出错了 -
你的代码 -
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
您的代码将陷入无限循环,因为循环永远不会跳出循环。您正在增加投掷次数以及头/尾数。您只需要增加头/尾数而不是抛掷数。可以根据我上面的解决方案进行其他更改。