所以我在一些C ++之后开始学习python,我们在python上找到了掷骰子的概率。我的问题是,如果这个代码的更好版本更简单,并且显而易见":
def numsix(roll):
return len([dice for dice in roll if dice == 6])
sample = [[i] for i in range(1,7)]
for i in range(7):
sample = [x + [i] for x in sample for i in range (1,7)]
event = [roll for roll in sample if numsix(roll)==4]
print(len(event), "/" ,len(sample))
答案 0 :(得分:0)
那么,
我制作了另一个更长但更清晰的代码版本。这段代码和上面的代码计算了当我们掷八个骰子时有四个六的概率 这是代码的v2:
def numSix(roll):
return len([dice for dice in roll if dice == 6])
r = range(1,7)
sample = [(i,j,k,l,m,n,o,p) for i in r for j in r for k in r for l in r \
for m in r for n in r for o in r for p in r]
event = [roll for roll in sample if numSix(roll) == 4]
print (len(event), "/" ,len(sample))
欢迎任何其他提示。感谢批评-__-。