在看到所有数字之前,您需要掷骰子的次数是多少?
我被要求定义一个运行蒙特卡罗模拟的函数,该模拟返回上述问题的估计值。我对解决方案的理解是我需要:
- 定义一个将试验次数作为输入的函数
- 生成 1 到 6 之间的随机整数(骰子的面数)
- 如果该整数尚不在列表中,则将该整数存储在列表中
- 计算达到上述条件所需的试验次数,并返回该计数
我对编程特别是Python相当陌生,所以我很难确定为什么我的语法在调用函数时没有产生输出,并希望有人可以帮助引导我走向正确的方向
这是我的代码:
def roll(n=1000):
trials = []
sides = 6
start = 1
for i in range (n):
for x in range (sides):
collection = [random.randint(1,sides)]
while any([x not in collection]):
collection.append(random.randint(1,6))
trials.append(len(collection))
return sum(trials)/ len(trials)
最佳答案
您可能不会打印函数返回的任何内容 - 这就是为什么它什么也不显示。
使用 print(roll())
而不是 roll()
来打印得到的结果。
您的循环太多,并且您的解决方案使用了太多的内存空间。
考虑一下运气不好,必须掷 1.000.000.000.000 次才能获得前 6 个 - 您将在列表中保存 1.000.000.000.000 个其他数字..这会占用大量内存。
您可以使用集合
来记住看到的数字,并使用计数器来计算找到所有数字所需的时间:
def roll(sides=6, n=1000):
"""Tests 'n' times to roll all numbers from 1 to 'sides' randomly.
Returns average tries needed to see all numbers over 'n' tries."""
trials = [] # collects all sinly tried counters
for _ in range(n):
seen = set() # empty, will only ever store 6 elements at most
tried = 0 # how long did it take to find all 6?
while len(seen) < sides: # use sides here as well
seen.add(random.randint(1,sides))
tried += 1
trials.append(tried)
return sum(trials)/n
print(roll())
输出(4 开始):
14.878
14.694
14.732
14.516
关于python - python 中的简单蒙特卡罗模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55076256/