繁体   English   中英

Python 带功能的抛硬币

[英]Python coin flip with functions

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

def flipCoin() - 以与硬币相同的概率返回“H”或“T”。

def simulate(numFlips) - 模拟掷硬币 numFlips(100) 次。 这个 function 返回包含 H 和 T 的长度为 numFlips 的列表。

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

在主function中,写一个测试循环,模拟该过程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() function 10000 次。 但实际上,您必须运行它一次,但会返回一个包含 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()

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

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

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM