我正在从Timothy Budd的Exploring Python一书中学习 Python。本章的练习之一是:
15. randint
random 模块的函数可用于产生随机数。例如,对 的调用random.randint(1, 6)
将以相等的概率产生值 1 到 6。编写一个循环 1000 次的程序。在每次迭代中,它都会调用两次randint
来模拟掷骰子。计算两个骰子的总和,并记录每个值出现的次数。在循环之后,打印总和数组。您可以使用本章前面显示的惯用语来初始化数组:
times = [0] * 12 # make an array of 12 elements, initially zero
我可以在数组中打印总和,但我不明白记录每个值出现的次数的概念。另外,有什么目的times = [0]
?这是我打印总和的代码:
#############################################
# Program to print the sum of dice rolls #
#############################################
from random import randint
import sys
times = [0] * 12
summation = []
def diceroll():
print "This program will print the"
print "sum of numbers, which appears"
print "after each time the dice is rolled."
print "The program will be called 1000 times"
for i in range(1,1000):
num1 = randint(1,6)
num2 = randint(1,6)
sum = num1 + num2
summation.append(sum)
#times[i] = [i] * 12
print summation
#print times
diceroll()