Vik*_*tor -2 python random simulation
当我运行下面的程序时,总数不是1000.我不知道出了什么问题.
在1000次掷骰子中,有:
这总计为666卷骰子.
我想具体说一下,如果还有什么我不清楚的地方,请告诉我.谢谢大家:)
#this is a program that simulate how many times that there will be for every sides of a dice, when I trying to throw it 1,000 times.
from random import randrange
def toss():
if randrange(6) == 0:
return "1"
elif randrange(6) ==1:
return "2"
elif randrange(6) ==2:
return "3"
elif randrange(6) ==3:
return "4"
elif randrange(6) ==4:
return "5"
elif randrange(6) ==5:
return "6"
def roll_dice(n):
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
for i in range(n):
dice = toss()
if dice == "1":
count1 = count1 + 1
if dice == "2":
count2 = count2 + 1
if dice == "3":
count3 = count3 + 1
if dice =="4":
count4 = count4 + 1
if dice == "5":
count5 = count5 + 1
if dice == "6":
count6 = count6 + 1
print ("In", n, "tosses of a dice, there were", count1, "for 1 and",
count2, "for 2 and", count3, "for 3 and", count4, "for 4 and", count5, "for
5 and",count6, "for 6.")
roll_dice(1000)
Run Code Online (Sandbox Code Playgroud)
您正在调用randrange(6)
所有if/elif
测试,因此值不同(它是随机的)并且您可能最终None
从您的toss
函数返回(并且您错过了一些计数)
存储randrange(6)
在变量中,然后测试它.
有更好的方法来做这个BTW,例如一个等效但工作:
def toss():
return str(randrange(6)+1)
Run Code Online (Sandbox Code Playgroud)
但是有一种更快捷的方式使用collections.Counter
和生成器理解来随机生成从1到6的1000个值:
import collections
import random
c = collections.Counter(random.randint(1,6) for _ in range(1000))
print(c)
print(sum(c.values()))
Run Code Online (Sandbox Code Playgroud)
我得到那两条输出线(首先是dict计算数字和滚动总数):
Counter({3: 199, 2: 172, 1: 160, 5: 160, 4: 158, 6: 151})
1000
Run Code Online (Sandbox Code Playgroud)
现在我有我的1000个值:)
归档时间: |
|
查看次数: |
71 次 |
最近记录: |