作业要求我们通过实验找出2到12的概率作为总和。我们想将两个骰子滚动1000次并计算总和为2、3,…和12的次数。到目前为止,我已经将其作为代码,但是我无法获得教授要求的输出。Output that the professor is looking for.我到目前为止所拥有的:
import random as r
die_1 = r.randint(1,6)
die_2 = r.randint(1,6)
print('For-Loop')
for i in range(2,13):
r.seed(1)
counter = 0
for j in range(1000):
if i == r.randint(2,12):
counter = counter + 1
print("sum = ", i, " count = ", counter)
from random import randint
rolls = [sum([randint(1, 6), randint(1, 6)]) for i in range(1000)]
for i in range(2, 13):
print(f'Sum of {i} was rolled {rolls.count(i)} times')
我试图解释评论中发生的一切:
from collections import defaultdict
from random import randint
# Roll the two dice how many times?
n = 1000
# Create a dictionary to store the results
results = defaultdict(int)
# Loop n times
for _ in range(n):
# Get random numbers for the two dice
die_1 = randint(1, 6)
die_2 = randint(1, 6)
# Increase the corresponding result by 1
results[die_1 + die_2] += 1
# Print results
print(results)
可能打印出以下内容:
defaultdict(<class 'int'>, {7: 160, 8: 134, 6: 145, 9: 107, 3: 50, 10: 76, 12: 26, 4: 86, 5: 128, 2: 37, 11: 51})
您还可以通过绘图轻松地说明结果:
import matplotlib.pyplot as plt
plt.bar(results.keys(), results.values())
plt.show()
您没有正确考虑概率。 r.randint(2, 12)
与独立滚动两个骰子不同(对于某些值,它们是多个两个骰子的总和为相同值)。
import collections
import random
print("For Loop")
occurrences = []
for trial in range(1000):
die1 = random.randint(1, 6)
die2 = random.randing(1, 6)
occurrences.append(die1 + die2)
counter = collections.Counter(occurrences)
for roll, count in counter.items():
print(f"sum = {roll} count = {count}")
如果您不想导入标准库的其他部分,则可以自己制作计数器。
import random
print("For Loop")
occurrences = {}
for trial in range(1000):
die1 = random.randint(1, 6)
die2 = random.randing(1, 6)
roll = die1 + die2
current = occurrences.setdefault(roll, 0)
occurrences[roll] = current + 1
for roll, count in occurrences.items():
print(f"sum = {roll} count = {count}")
请注意,输出将因所涉及的随机性而稍有不同。