我被困在python中的代码中,它接受骰子数和卷数并返回获得的数字总和。它还应该打印总和的直方图。我陷入了代码的第一部分。有人可以帮我解决这个问题吗?不知道我哪里错了。第二部分的任何帮助(返回直方图)将有助于我在python中学习它。
from random import choice
def roll(rolls,dice):
d = []
for _ in range(rolls):
d[sum(choice(range(1,7)) for _ in range(dice))] += 1
return(d)
答案 0 :(得分:1)
你的问题是你不能随意索引到一个空列表:
l = []
l[13] += 1 # fails with IndexError
相反,您可以使用defaultdict
,这是一种特殊类型的字典,如果尚未使用密钥,则不介意:
from collections import defaultdict
d = defaultdict(int) # default to integer (0)
d[13] += 1 # works fine, adds 1 to the default
或Counter
,专为此类案例设计(“提供方便快捷的方式”)并提供额外的便捷功能(如most_common(n)
),以获得n
最多常见条目):
from collections import Counter
c = Counter()
c[13] += 1
要手动使用标准dict
执行此操作,只需添加支票:
d = {}
if 13 in d: # already there
d[13] += 1 # increment
else: # not already there
d[13] = 1 # create
答案 1 :(得分:0)
试试这个,
from random import choice
import pylab
def roll( rolls, dice ):
s = list()
for d in range( dice ):
for r in range( rolls ):
s.append( choice( range(1,7) ) )
return s
s = roll( rolls, dice )
sum_of_rolls = sum( s )
# then to plot..
pylab.hist( s )
答案 2 :(得分:0)
这应该这样做
import random
def rolls(N, r): # N=number of dice. r=number of rolls
myDie = [1,2,3,4,5,6]
answer = {}
for _rolling in range(r):
rolls = []
for _die in range(N):
rolls.append(random.choice(myDie))
total = 0
for roll in rolls:
total += roll
if total not in answer:
answer[total] = 0
answer[total] += 1
return answer