计算“岩石,纸,剪刀”的平均值

时间:2018-05-26 08:24:38

标签: python average

昨晚,我一直想着自己在“Rock,Paper,Scissors”中连续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()

2 个答案:

答案 0 :(得分:1)

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

cmake && make

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

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

而不是这个,你可以像这样打印循环外的平均值

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

还有一件事,你只是在roll1!= roll2时增加num,这就增加了循环必须运行的次数 这是改变后程序出现的方式

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

答案是0,我想你连续10次不太可能。

答案 1 :(得分:0)

一些不言自明的代码(所以你也可以学习编写干净的代码):

import random

def get_10_outcomes():
    return [
        (random.randint(1, 3), random.randint(1, 3))
    ]

def have_we_got_10_in_a_row():
    return (
        len(set(get_10_outcomes()))
        == 1
    )

def how_many_10_in_a_row_in_10000():
    return len(list(filter(
        None,
        [have_we_got_10_in_a_row() for _ in range(10000)]
    )))

def get_chance_of_10_in_a_row():
    return how_many_10_in_a_row_in_10000() / 10000

chance = get_chance_of_10_in_a_row()
print('{:.3%}'.format(chance))