【发布时间】:2020-05-09 16:45:38
【问题描述】:
更快的编码方式?
我想知道是否有人可以建议一种更快的编码方式?我的任务是为 2-3 个骰子制作骰子滚动函数,并在直方图中显示结果。我知道 while/for 循环不是 python 中的禁食。谁能建议一个更快的内置函数来实现这一点?
import numpy as np
import matplotlib.pyplot as plt
#Write a function that will return a random int between 1-6
def roll_die():
x = np.random.random_integers(6)
return x
#A function to calculate the sum of 2 dice using a while loop
def rolling2(x):
n=0
while(n < rolls):
sum = roll_die() + roll_die()
arr[n] = sum
sum = 0
n = n + 1
#A function to calculate the sum of 3 dice using a while loop
def rolling3(x):
n=0
while(n < rolls):
sum = roll_die() + roll_die() + roll_die()
arr[n] = sum
sum = 0
n = n + 1
rolls = int (input("How many times will you roll 2 dice?"))
#Initialise 2 arrays to store values
arr = np.zeros(rolls)
arr1 = np.zeros(rolls)
#Calling rolling functions
rolling2(arr)
print (arr)
rolling3(arr1)
print(arr1)
#Plot graph using matplotlib methods and functions
fig, ax = plt.subplots(2,1)
ax[0].hist(arr, bins=11)
ax[0].set_xlabel("Sum of 2 Dice")
ax[0].set_label("Frequency")
ax[0].set_title("Frequency of the Sum of Rolling 2 dice")
ax[1].hist(arr, bins=16)
ax[1].set_xlabel("Sum of 3 Dice")
ax[1].set_label("Frequency")
ax[1].set_title("Frequency of the Sum of Rolling 3 dice")
plt.show()
【问题讨论】:
-
我建议进行代码审查 - codereview.stackexchange.com.
标签: python-3.x numpy matplotlib