滚动骰子的Python模拟的性能问题

时间:2017-01-09 03:28:51

标签: python performance simulation dice

我正在尝试模拟6张面部骰子卷并存储结果。即。

  1. 掷骰子一次 - 存储结果
  2. 掷骰子2次 - 存储结果
  3. 掷骰子3次 - 存储结果 ..等等..
  4. 后来,我计算每次迭代中每个数字出现的次数。对于较小的迭代,它可以很好地运行,但是当我为100,000次大数选择模拟时,代码需要永远模拟。

    如何使此代码高效?我将不胜感激任何建议。

    import random
    from collections import defaultdict
    from collections import Counter
    
    # How many time we want to roll a dice
    number_of_rolls = 100000
    
    # Define Blank Dictionary to store output of Dice rolls 
    roll = defaultdict(list)
    
    # Roll the dice and store output 
    for i in range(number_of_rolls):
        for j in range(i):
            roll[i].append(random.sample(dice,1)[0])
    
    # Count occurance of each number from dice roll
    obv = defaultdict(dict)
    for i in range(len(roll)):
        obv[i]=dict(Counter(roll[i]))
    

    谢谢, 拉马

0 个答案:

没有答案