编写一个函数collect_sims(nsim,N,D,p=0.5,nmax=10000),它运行run_sim函数nsim次(参数为N、D、p)并返回一个长度为nmax的numpy数组,给出的数量模拟执行指定步数后停止的次数。例如,假设 nsim 为 8,连续运行 run_sim 会得到 3,4,4,3,6,5,4,4。您可以将其制表为“两个 3、四个 4、一个 5、一个 6、零个 7、零个 8……”
def collect_sims(nsim, N, D, p=0.5, nmax=10000):
run_sim(N=20, D=6, p=0.5, itmax=5000)
onecount = 0
twocount = 0
threecount = 0
fourcount = 0
fivecount = 0
sixcount = 0
for k in range (n):
if D == 1:
onecount += 1
if D == 2:
twocount += 1
if D == 3:
threecount += 1
if D == 4:
fourcount += 1
if D == 5:
fivecount += 1
if D == 6:
sixcount += 1
return(k)
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
它说我的 6 个变量 onecount、twocount 等未定义,我该如何定义它们?另外,我可以做什么来修复我的代码?
最佳答案
我不知道你为什么要返回 k。
无论如何,问题是 oncount、twocount 等位于不同的打印范围内。您可以将 print() 放在函数内,也可以返回包含计数的元组
有些是这样的:
def collect_sims(nsim, N, D, p=0.5, nmax=10000):
run_sim(N=20, D=6, p=0.5, itmax=5000)
onecount = 0
twocount = 0
threecount = 0
fourcount = 0
fivecount = 0
sixcount = 0
for k in range (n):
if D == 1:
onecount += 1
if D == 2:
twocount += 1
if D == 3:
threecount += 1
if D == 4:
fourcount += 1
if D == 5:
fivecount += 1
if D == 6:
sixcount += 1
return(onecount, twocount, threecount, fourcount,fivecount,sixcount)
onecount, twocount, threecount, fourcount,fivecount,sixcount = collect_sims (...)
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
不同的解决方案
也许这个其他解决方案可以帮助您:
关于Python 骰子结果计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262697/