Python 带函数的硬币翻转

Python coin flip with functions

我需要创建一个 python 程序,该程序将使用各种函数来模拟抛硬币 100 次并在 10,000 次尝试中找到最大的“H”连胜。我坚持如何完成 def main() 函数,特别是计数器。我也不知道我的程序是否正确计算了条纹。

def flipCoin() - returns 'H' 或 'T' 概率与硬币相同。

def simulate(numFlips) - 模拟掷硬币 numFlips(100) 次。此函数 returns 包含 H 和 T 的长度为 numFlips 的列表。

def countStreak(flips_list) - 遍历传递给它的翻转列表并计算 'H's 的条纹和 returns 它找到的最大条纹。在两个单独的变量中跟踪当前的正面数和当前最大的正面连续数。 当您遍历列表时,请跟踪您在一行中看到的当前正面数量。如果您看到尾巴,请检查当前的正面连胜是否大于您当前的最长连胜。如果是这样,请保存当前连胜。然后重置你的人头计数器。

在main函数中,编写一个模拟该过程10000次的测试循环。 跟踪当前最大的正面连胜,并在测试循环完成后显示此结果。

# import statements                                                             
import random

# function defintions                                                           
def flip():
    coin = random.randint(0, 1)
    if coin == 0:
        return "H"
    else:
        return "T"

def simulate(num_flips):
# simulates numFlips coin flips                                             
# returns a list of the flips
    numFlips = []
    for i in range(100):
        numFlips.append(flip())
    return numFlips

def countStreak(flips_list):
# iterates through the 'flips' list                                         
# returns number of 'H's
    count = 0
    maxCount = 0
    flips_list = simulate()
    for i in flips_list:
        if i == "H":
            count += 1
            if count > maxCount:
                maxCount = count
        else:
            count = 0
    return maxCount

def main():
    for j in range(10000):
        trial = simulate(100)
        coinFlip = countStreak(1)
        # need something here to track count of streaks for "H"
    print("The longest streak of heads was " + str(coinFlip) +".")


if __name__ == "__main__":
    main()

所以您的代码中存在缺陷,您 运行宁 simulate() 函数 10000 次。但实际上,您必须 运行 它一次,但 return 一个包含 10000 个项目的列表。此外,您不需要每次都检查条纹,因此 check_streak() 需要跳出循环,我们需要将 simulate(10000) 获得的结果传递给它。 正确代码:

# import statements                                                             
import random

# function defintions                                                           
def flip():
    coin = random.randint(0, 1) # better option would be to use random.choice()
    if coin == 0:
        return "H"
    else:
        return "T"

def simulate(num):
# simulates numFlips coin flips                                             
# returns a list of the flips
    numFlips = []
    for i in range(num): # this needs to run num times
        numFlips.append(flip())
    return numFlips

def countStreak(flips_list):
# iterates through the 'flips' list                                         
# returns number of 'H's
    count = 0
    maxCount = 0
    for i in flips_list:
        if i == "H":
            count += 1
            if count > maxCount:
                maxCount = count
        else:
            count = 0
    return maxCount

def main():
    trial = []
    for j in range(10000):
        temp2 = simulate(100) # SImulate 10000 coin flips
        coinFlip = countStreak(temp2) # Check streak of variable trial
        trial.append(coinFlip)
        # need something here to track count of streaks for "H"
    # print(trial)
    print("The longest streak of heads was " + str(max(trial)) +".")

if __name__ == "__main__":
    main()

这部分是可选的,用于优化

虽然逻辑没有错,但是不用排在第一位再查连胜,直接一起查就可以了,时间会少,而且space。
另外,你的逻辑是正确的,但是这个会更好:

import random

# function defintions                                                           
def flip():
    return random.choice(['H', 'T']) # using random.choice()

def simulate(num_flips):
    streak = 0
    temp = 0    
    for i in range(num_flips):
        if flip() == 'H':
            temp+=1 # adding one to temporary streak if it is a heads
        else: # this block executes if streak is broken
            if temp > streak:
                streak = temp
            temp = 0
    return streak

def main():
    trial = []
    for i in range(10000):
        trial.append(simulate(100))
    print("The longest streak of heads was " + str(max(trial)) +".")


if __name__ == "__main__":
    main()