gpt4 book ai didi

python - 计算 "Rock, Paper, Scissors"中的平均值

转载 作者:行者123 更新时间:2023-12-01 09:24:33 28 4
gpt4 key购买 nike

昨晚我在想“石头剪刀布”连续 10 次得到相同结果的概率。我想出了如何做到这一点并完成了该任务,但后来我想挑战一下自己,所以我想调整该程序,使其运行初始程序多次(10,000),然后输出平均结果,我将其希望接近连续 10 次获得相同结果的概率。请注意,我没有考虑战术,只是两个玩家随机选择 r、p 或 s。

def rps():

num=0 # num is the number of times i want the programme to run while roll<10:
total=0 # this should be close to 3^10 * 10000, its the result of all the tries added together

while num <10001:
tries=0 # this is how many times the programme has tried to get p1=p2
roll=0 # this is the amount of times it has counted p1=p2 (it gets re-set everytime it reaches 10)
import random
while roll <10:
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll=roll+1
else:
tries=tries + 1
roll=0
num=num+1
if roll==10:
total=total+roll
roll=0
if num==10000:
print (num)
print (total/num)
rps()

最佳答案

程序有很多问题,这一次,第二个for循环没有任何用处,我知道你正在使用第二个for循环来重置计数器,如果连续滚动的数量达到10 ,但你已经在这里这样做了

if roll==10:
total=total+roll
roll=0

通过设置 roll=0,您将重置它。另外,最后一个 if 条件增加了复杂性,

if num==10000:
print (num)
print (total/num)

除此之外,您还可以像这样在循环外打印平均值

if roll==10:
total=total+roll
roll=0
print (total/10000) #this being outside the while loop

还有一件事,仅当 roll1 != roll2 时才递增 num,这会增加循环必须运行的次数修改后程序是这样的

import random
def rps():
num=0 #num is the number of times i want the programme to run while roll<10:
total=0 #this should be close to 3^10 * 10000, its the result of all the tries added together
roll = 0
while num <10001:
tries=0 #this is how many times the programme has tried to get p1=p2
p1=random.randint(1,3)
p2=random.randint(1,3)
if p1==p2:
roll = roll+1
else:
tries = tries + 1
roll = 0
if roll==10:
print(roll)
total += roll
roll=0
num = num + 1
print (total/10000)
print(tries)
rps()

答案是 0,我猜你连续得到 10 的可能性很小。

关于python - 计算 "Rock, Paper, Scissors"中的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50540817/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com