我已经为一个程序编写了代码,该程序从用户那里获取边数,并将其中两个骰子掷1000次,然后在直方图上显示总和
我如何做同样的事情,但用户可以选择不同的骰子,例如6面和8面骰子
这是我的类似骰子代码:
from random import randint
import matplotlib.pyplot as plt
from collections import defaultdict
#Asking for the sides
n = int(input("How many sides? 6, 8 or 10?\n"))
number = 1000 #How many times it's rolled
#Making empty dictionaries for each type of die
sums6 = defaultdict(int)
sums8 = defaultdict(int)
sums10 = defaultdict(int)
#Making conditions for each type and plotting the histograms
if n == 6:
for _ in range(number):
die1 = randint(1,6)
die2 = randint(1,6)
sums6[die1 + die2] += 1
plt.bar(list(sums6.keys()), sums6.values(), color='b')
plt.xlabel('Result')
plt.ylabel('Frequency of Result')
plt.grid(axis='y', alpha=0.5)
plt.show()
if n == 8:
for _ in range(number):
die1 = randint(1,8)
die2 = randint(1,8)
sums8[die1 + die2] += 1
plt.bar(list(sums8.keys()), sums8.values(), color='g')
plt.xlabel('Result')
plt.ylabel('Frequency of Result')
plt.grid(axis='y', alpha=0.5)
plt.show()
if n == 10:
for _ in range(number):
die1 = randint(1,10)
die2 = randint(1,10)
sums10[die1 + die2] += 1
plt.bar(list(sums10.keys()), sums10.values(), color='r')
plt.xlabel('Result')
plt.ylabel('Frequency of Result')
plt.grid(axis='y', alpha=0.5)
plt.show()
如果您只希望用户能够在一个骰子中输入多个边,则只需将2个变量作为输入并从中生成随机数,也无需添加条件,您只需在randint本身中指定骰子中选定的边数
要求用户提供逗号分隔的边数,然后使程序适用于任意边数的骰子:
例如:
相关问题 更多 >
编程相关推荐