繁体   English   中英

在 Python 中掷骰子

[英]roll dice in Python

我需要找到我需要掷一个公平骰子的 100 次的期望值,直到我得到所有六个数字

这是我的代码。 我不知道如何将其放入 while 循环 100 次。 任何人都可以帮忙吗?

例如:我第一次掷出所有六个数字时,我需要掷出 8 次。 我第二次掷到所有六个数字,我掷了13次然后我记录如下:1:8 2:13... 100:9

我想要我的 a=[8,13,.....,9]

import random
trials = []
a=[]
collection = [random.randint(1,6) for x in range(6)]
for c in collection:
    if c not in a:
        a.append(c)
    
    else:
        collection.append(random.randint(1,6))
trials.append(len(collection))

print(a)
print(collection)
print(trials)

算法:

  • 为结果创建空字典
  • 做100次
    • 创建一组数字 1-6
    • 创建此尝试绘制数字的空列表
    • 虽然集合中仍有数字重复:
      • 画一个数字并将其添加到您的列表中
      • 如果在其中,则从集合中删除数字
    • 将列表添加到字典
  • 评估东西

或在代码中:

import random

results = {}

for t in range(100):
    nums = set((1,2,3,4,5,6))
    data = []
    # do as long as we still lack one number
    while nums:
        n = random.randint(1,6)
        data.append(n)
        # remove if in, else we dont care
        if n in nums:
            nums.remove(n)
    # add the list to your results - if you just need the lenghts don't
    # store the whole list here, just store its lenghts and adapt the 
    # evaluation code
    results[t] = data

# evaluation
lengths = [len(w) for w in results.values()]

average_lengths = sum(l for l in lengths) / 100
max_lengths = max(lengths)
min_lengths = min(lengths)

# output
print(min_lengths, average_lengths, max_lengths)

Output:

6 13.95 31 

您可以打印字典results以查看所有掷骰子。
您可以打印列表lenghts以查看所有 100 个不同的长度。

你可以像这样循环它:

import random
n = 1
trials = []
while n<=100:
    a=[]
    collection = [random.randint(1,6) for x in range(6)]
    for c in collection:
        if c not in a:
            a.append(c)
        
        else:
            collection.append(random.randint(1,6))
    trials.append(len(collection))
    n += 1
    print(a)
    print(collection)
    print(trials)

只需执行n = 1while n <= 100n += 1

这是平均代码:

import random
n = 1
trials = []
while n<=100:
    a=[]
    collection = [random.randint(1,6) for x in range(6)]
    for c in collection:
        if c not in a:
            a.append(c)
        
        else:
            collection.append(random.randint(1,6))
    trials.append(len(collection))
    n += 1
    #print(a)
    #print(collection)
    #print(trials)
print(sum(trials) / len(trials))

以下是否按要求工作?:

from random import randint

trials = []
goal = set(list(range(1, 7)))
for _ in range(100):
    attempts = 0
    cur = set()
    while cur != goal:
        cur.add(randint(1, 6))
        attempts += 1
    trials.append(attempts)

只需将 for 循环包装在另一个循环中:

for i in range(100):
    a = []
    for c in coll:
        if c not in a:
            a.append(c)
        else:
            coll.append(random.randint(1, 6))
    trials.append(len(coll))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM