random 模块中的函数
可用于生成随机数。例如,调用randint
将以相同的概率生成值 1 到 6。编写一个循环 1000 次的程序。在每次迭代中,它都会对random.randint(1, 6)
进行两次调用来模拟掷骰子。计算两个骰子的总和,并记录每个值出现的次数。randint
输出应该是两列。一个显示所有总和(即从 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
但是,我没有得到任何结果。
您不应该使用
Sum
,因为简单变量不应大写。
您不应该使用
sum
,因为这会遮盖内置 sum()
。
使用不同的非大写变量名称。我建议
diceSum
;这也说明了一些关于上下文、程序背后的想法等,以便读者更快地理解它。
您不想让您的代码的任何读者满意吗?再想一想。您在这里寻求帮助;-)
试试这个:
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
sum
存在语法大小写错误python 使用的种子生成器应该足以满足您的任务。
看起来像是一个拼写错误。
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])
随机导入 频率字典={} 对于范围(100)内的 i: 数字=随机.randint(1,10) 如果频率_字典中的数字: Frequency_dict[数字] +=1 别的: Frequency_dict[数字] =1 对于Frequency_dict中的键: print(f'{"数字":<10}',f'{"Frequency":<10}') print(f'{key:<10}',f'{frequency_dict[key]:<10}')