我必须为我的计算机类做一个骰子滚动程序。我选择用Python编写我的。但是,当我执行它时,它会打印1000次数字列表。这是代码。任何帮助将不胜感激。
`
import random
def rollDie():
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0
ten = 0
eleven = 0
twelve = 0
for i in range(0, 1000):
roll = int(random.randint(1,6)) + (random.randint(1,6))
if roll == 2:
two = two+1
elif roll == 3:
three = three+1
elif roll == 4:
four = four+1
elif roll == 5:
five = five+1
elif roll == 6:
six = six+1
elif roll == 7:
seven = six+1
elif roll == 8:
eight = eight+1
elif roll == 9:
nine = nine+1
elif roll == 10:
ten = ten+1
elif roll == 11:
eleven = eleven+1
elif roll == 12:
twelve = twelve+1
print "2:%s" % two
print "3:%s" % three
print "4:%s" % four
print "5:%s" % five
print "6:%s" % six
print "7:%s" % seven
print "8:%s" % eight
print "9:%s" % nine
print "10:%s" % ten
print "11:%s" % eleven
print "12:%s" % twelve
rollDie()
`
谢谢!
答案 0 :(得分:1)
我的猜测是你在文本编辑器中的缩进是关闭的; print语句包含在for
循环中。你也有一点问题,你打电话给seven = six+1
。以下是您编辑过的代码,请尝试将此粘贴到您的文件中:
import random
def rollDie():
one = 0
two = 0
three = 0
four = 0
five = 0
six = 0
seven = 0
eight = 0
nine = 0
ten = 0
eleven = 0
twelve = 0
for i in range(0, 1000):
roll = int(random.randint(1,6)) + (random.randint(1,6))
if roll == 2:
two = two+1
elif roll == 3:
three = three+1
elif roll == 4:
four = four+1
elif roll == 5:
five = five+1
elif roll == 6:
six = six+1
elif roll == 7:
seven = seven+1
elif roll == 8:
eight = eight+1
elif roll == 9:
nine = nine+1
elif roll == 10:
ten = ten+1
elif roll == 11:
eleven = eleven+1
elif roll == 12:
twelve = twelve+1
print "2:%s" % two
print "3:%s" % three
print "4:%s" % four
print "5:%s" % five
print "6:%s" % six
print "7:%s" % seven
print "8:%s" % eight
print "9:%s" % nine
print "10:%s" % ten
print "11:%s" % eleven
print "12:%s" % twelve
rollDie()
此外,您的代码效率极低;请尝试使用以下代码:
import random
rolls = {}
for k in range(2, 13):
rolls[k] = 0
for k in range(1000):
roll = random.randint(1, 6)+random.randint(1, 6)
rolls[roll]+=1
for k in rolls:
print '%d occurred %d times!' %(k, rolls[k])
运行如下:
bash-3.2$
2 occurred 38 times!
3 occurred 51 times!
4 occurred 90 times!
5 occurred 99 times!
6 occurred 136 times!
7 occurred 173 times!
8 occurred 151 times!
9 occurred 90 times!
10 occurred 92 times!
11 occurred 58 times!
12 occurred 22 times!
bash-3.2$
如果我们计划时间,这是你的时间:
This ran in 0.06672 seconds!
这是我的:
This ran in 0.004228 seconds!
当然,这可能只是我的电脑给出了如此大的差异:)。如果您想知道我如何计时,我使用了time.time() - previous time.time()
。
答案 1 :(得分:0)
没有变量,我们可以用相同的方式实现掷骰子的相同功能:
import random
from collections import Counter,OrderedDict
def ran(i):
roll = int(random.randint(1,6)) + (random.randint(1,6))
return roll
for i,j in OrderedDict(Counter(map(ran,range(1,1000)))).items():
print i,":", j
说明:首先我们将rand int的所有值存储在dict.map链接中。 然后usinf counter v可以找到所有频率然后odered dict用于根据键排序,即2号的第一个等等。