【发布时间】:2012-08-15 05:58:31
【问题描述】:
我正在从 Timothy Budd 的 Exploring Python 一书中学习 Python。本章的一个练习是这样的:
15。 random 模块中的函数randint 可用于生成随机数。例如,对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()
【问题讨论】:
标签: python python-3.x