编写一个函数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等没有定义,我该如何定义它们?另外,我该怎么做才能修复我的代码?
答案 0 :(得分:1)
我不知道你为什么要回来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")
不同解决方案
也许这个其他解决方案可以帮到你:
答案 1 :(得分:0)
缩进 for 循环:在您发布的代码中,它返回原始缩进级别(无<,用于语句)。这结束了你的功能,循环在主程序中。您的变量尚未定义(因为它们与函数中的变量不同),而您的返回是非法的。
或许试试这个?
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
print(onecount, "1",twocount,"2",threecount,"3",fourcount,"4",fivecount,"5",sixcount,"6")
collect_sims()
我无法测试,因为您没有提供足够的代码。另请注意,我只是将 print 语句保留为调试跟踪。你必须返回一个阵列,而你还没有尝试过这样做。您的原始代码返回 k ,必须为n + 1。这对调用程序没用。
进一步提供帮助
学习使用6个元素的列表作为计数,而不是六个单独的变量。更好的是,将所有模具卷放入一个列表中,只需使用计数功能来确定每个模具的数量。