2014-01-08 95 views
0

来自随机模块的函数randint可用于生成随机数。例如,在random.randint(1, 6)上的调用将以相等的概率产生值1到6。编写循环1000次的程序。在每次迭代时,它会在randint上进行两次调用来模拟滚动一对骰子。计算两个骰子的总和,并记录每个值出现的次数。Python随机数及其频率

输出应该是两列。一个显示所有的总和(即从2到12),另一个显示1000次总和的相应频率。

我的代码如下所示:

import random 
freq=[0]*13 

for i in range(1000): 
    Sum=random.randint(1,6)+random.randint(1,6) 
    #compute the sum of two random numbers 
    freq[sum]+=1 
    #add on the frequency of a particular sum 

for Sum in xrange(2,13): 
    print Sum, freq[Sum] 
    #Print a column of sums and a column of their frequencies 

但是,我没能得到任何结果。

+0

是否有可能告诉我们会发生什么呢? – glglgl

+1

@PedrodelSol也许,但为什么不呢?他们自己制造了主要部件,现在正在寻求提示。 – glglgl

+1

你的意思是你的代码片段包含意外的缩进,并且应该将'freq + + 1'编辑为'freq [Sum] + = 1'? – zhangxaochen

回答

1

修改后的代码你不应该使用Sum,因为简单变量不应该大写。

您不应该使用sum,因为这会影响内置的sum()

使用不同的非大写变量名称。我建议diceSum;这也说明了上下文,程序背后的想法等等,以便读者更快地理解它。

你不想让你的代码读者快乐吗?再想一想。你在这里寻求帮助;-)

0

试试这个:

import random 
freq=[0]*13 

for i in range(1000): 
    Sum=random.randint(1,6)+random.randint(1,6) 
    #compute the sum of two random numbers 
    freq[Sum]+=1 
    #add on the frequency of a particular sum 

for Sum in xrange(2,13): 
    print Sum, freq[Sum] 
    #Print a column of sums and a column of their frequencies 

有上总和

种子发生器Python使用应该足够给你的任务语法错误的情况下。

+0

这是完全相同的代码,使用不同的缩进和添加了'#!'shebang - 至少在我的PC上,它不起作用,因为我的Python没有安装在/ usr/local /下。最好提示'#!/ usr/bin/env python'或'#!/ usr/bin/env python2.7'。 – glglgl

+0

我同意,删除它。 –

+0

噢,好的。我没有看到“总和”拼写。 – glglgl

0

看起来像一个错字错误。 Sum变量被错误地输入为sum

下面是Python 3.x都有

#!/usr/bin/env python3 

import random 

freq= [0]*13 

for i in range(1000): 
    #compute the sum of two random numbers 
    Sum = random.randint(1,6)+random.randint(1,6) 

    #add on the frequency of a particular sum 
    freq[Sum] += 1 

for Sum in range(2,13): 
    #Print a column of sums and a column of their frequencies 
    print(Sum, freq[Sum])