Skip to content

Instantly share code, notes, and snippets.

@niyumard niyumard/rolldice.py
Created Feb 10, 2019

Embed
What would you like to do?
Draw chart for rolling dice for k times
import random
import matplotlib.pyplot as plt
#How many times do you want the loop to run?
howmanytimes = 1000000
k = 4
def dice():
r = ''
for j in range(0,k):
r += str(random.randint(1,6))
return r
x = []
for i in range(0,howmanytimes):
x.append(dice())
d = {}
for i in range(k,k*6+1):
d[i] = 0
for i in x:
t = 0
for j in range(0,len(i)):
t += int(i[j])
d[t] += 1
for i in d:
d[i] = d[i]/len(x)
sumofprobabilities = 0
for i in d:
sumofprobabilities += d[i]
expectedvalue = 0
for i in d:
expectedvalue += d[i]*i
print(d)
print("Sum of Probabilities:", sumofprobabilities)
print("Expected Value:", expectedvalue)
plt.bar(range(len(d)), list(d.values()), align='center')
plt.xticks(range(len(d)), list(d.keys()))
plt.suptitle('If we roll the dice '+str(k)+' times')
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.