我是编程新手,遇到了一个我似乎无法调试的错误,无论我做了什么改动。我试图编写一个函数,允许用户指定翻转次数和连续连续条纹翻转的长度。该程序应该计算条纹(头部或尾部)发生的次数。当我运行当前程序时,我会为头部和尾部返回值1:
import random
def flip():
flipValue = random.randint(1,2)
if flipValue == 1:
side = "Heads"
else:
side = "Tails"
return side
def nStreak():
numFlips = int(input("Number of flips:"))
lengthStreak = int(input("Length of streak:"))
numRuns = 0
heads = 0
tails = 0
numStreakHeads = 0
numStreakTails = 0
while numRuns != numFlips:
side = flip()
numRuns += 1
if side == "Heads":
heads += 1
if heads == lengthStreak:
numStreakHeads += 1
if side == "Tails":
tails += 1
if tails == lengthStreak:
numStreakTails += 1
print("Number of heads streaks:", numStreakHeads)
print("Number of tails streaks:", numStreakTails)
答案 0 :(得分:0)
首先,在你到达lendthStreak后,你没有重置你的计数器。所以有一次,比如说,head等于lendthStreak,它每次都会比lendthStreak更大,因此你总会得到1的结果。你想在遇到条纹后重置那个值。你还需要在翻转另一侧时重置你的计数器(一旦你翻转头,设置尾巴= 0)。
{{1}}