Performance issue with Python simulation for rolling dice

30 Views Asked by At

I am trying to simulate 6 face Dice Rolls and store the outcomes. i.e.

  1. Roll dice once - store outcome
  2. Roll dice 2 times - store outcomes
  3. Roll dice 3 times - store outcomes .. and so on..

Later, I am counting how many times each digit appeared in each iteration. For smaller iterations it runs fine, but when I choose simulation for large numbers like 100,000 times the code takes forever to simulate.

How can I make this code efficient? I would appreciate any suggestions.

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]))

Thanks, Rama

0

There are 0 best solutions below