模拟滚动骰子的程序,并告诉您滚动每个数字的次数

时间:2014-12-01 01:21:33

标签: python list for-loop count dice

我是初学者,我必须创建一个模拟滚动骰子10000次的程序,然后告诉用户他们滚动每个数字的次数。困难的是,我必须只使用两个变量。

import random
count1=0
count2=0
count3=0
count4=0
count5=0 
count6=0
dice=random.randint(1,7)
for i in range(10000):
    if dice==1:
        count1+=1
    if dice==2:
        count2+=1
    if dice==3:
        count3+=1
    if dice==4:
        count4+=1
    if dice==5:
        count5+=1
    if dice==6:
        count6+=1
print "You entered "+ str(count1)+ " ones, " + str(count2) + " twos, "+str(count3) + " threes, " +str(count4)+ " fours, " +str(count5)+ " fives, and "+str(count6) +" sixes."

问题是,我无法让程序选择多个随机数,它只会重复相同的数字10000次。另外,正如你所看到的,我不知道如何只用两个变量编写这个程序,但我认为它可能与列表有关。

4 个答案:

答案 0 :(得分:1)

您需要将行dice=random.randint(1,7)放在for循环中。

答案 1 :(得分:0)

你可以使用字典:

import random
from collections import defaultdict
dice = defaultdict(int)
for x in range(10000):
    dice[random.randint(1,6)] += 1
print(dice)

答案 2 :(得分:0)

你的立即问题是你在循环开始之前得到一次的随机值,然后每次循环使用那个单值。要解决此问题,应将random.randint()的调用移动到循环:

for i in range(10000):
    dice=random.randint(1,7)
    if dice==1:

其次,你拥有的电话会给你1到7之间的数字,除非你使用一些奇怪的Dungeons and Dragons风格的骰子,否则可能不是你想要的。您应该生成从1到6的数字,或者如下所示,数组为0到5。

第三,如果您仅限于两个变量,那么几乎可以保证您将这些变量与循环计数器和计数值数组一起使用,留下任何剩余的骰子投掷和个人计数变量。

所以你需要类似下面的伪代码:

dim count[1..6]
for i = 1 to 6 inclusive:
    count[i] = 0
for i = 1 to 10000 inclusive:
    count[random(1..6)] += 1
for i = 1 to 6 inclusive:
    output "Dice value ", i, " occurred ", count[i], " times."

如果这是课堂作业,我建议您立即停止阅读并基于此实施自己的解决方案。如果它不是课堂作业,或者你的道德规范不像(a)那样强大,下面的Python代码就会显示一种方法,记住Python数组是从零开始的而不是从一开始的:

import random

count = [0, 0, 0, 0, 0, 0]

for i in range(10000):
    count[random.randint(0,5)] += 1

for i in range(6):
    print "Value %d happened %d times" % (i + 1, count[i])

(a)请注意,SO是一个相当知名的网站,您的教育工作者可能会根据他们在网上找到的内容检查课堂作业。

答案 3 :(得分:-1)

因为你把dice=random.randint(1,7)放在循环之外,当然这只会生成一个数字。

我稍后会为“仅两个变量”添加代码。看起来像一个有趣的问题。