你的
while
条件不能表达你所期望的。你可能想用列表理解
while any([x not in collection for x in [1, 2, 3, 4, 5, 6])
另外,你不需要三层循环,只需要两层:一层
for
每次审判
虽然
审判尚未完成。一个有效的例子,接近你原来的职位
import random
def roll(n=1000):
trials = []
sides = 6
start = 1
possible_sides = [1, 2, 3, 4, 5, 6]
for i in range (n):
collection = [random.randint(1,sides)]
while any([side not in collection for side in possible_sides]):
collection.append(random.randint(1,6))
trials.append(len(collection))
return sum(trials)/ len(trials)
而更有效的解决方案
set
有效地执行与以前的解决方案相同的操作
any([side not in collection for side in possible_sides])
:
import random
def roll(n=1000):
trials = []
sides = 6
start = 1
possible_sides = set([1, 2, 3, 4, 5, 6])
for i in range (n):
n_rolls = 0
sides_rolled = set()
while not sides_rolled == possible_sides:
sides_rolled.add(random.randint(1, sides))
n_rolls += 1
trials.append(n_rolls)
return sum(trials)/ len(trials)
或者,更有效的是,检查一下
len(sides_rolled) < 6
,正如帕特里克·阿特纳在回答中指出的那样。