编写一个collect_sim函数(nsim,N,D,p=0.5,nmax=10000),它运行run_sim函数nsim times(参数N,D,p),并返回一个numpy数组,该数组的长度为nmax,给出模拟在指定步数下停止的次数。例如,假设nsim为8,连续运行run_sim得到3,4,4,3,6,5,4,4。你可以把它列为“两个3,4个4,1个5,1个6,0 7,0 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。。。etc在不同的打印范围内。可以将print()放入函数中,也可以返回一个包含计数的元组
像这样的人:
不同的解决方案
也许这另一个解决方案可以帮助您:
https://stackoverflow.com/a/9744274/6237334
缩进for循环:在您发布的代码中,它回到原始缩进级别(none,对于for语句)。这就结束了函数,循环在主程序中。您的变量尚未定义(因为它们与函数中的变量不同),并且您的返回值是非法的。在
试试这个吧?在
我不能测试,因为你没有提供足够的代码。另外,请注意,我只是将print语句留在原处作为调试跟踪。你必须返回一个数组,但你还没有尝试这么做。原始代码返回的值必须是n+1。这对调用程序没有用处。在
进一步帮助
学习使用6个元素的列表来计算计数,而不是使用六个单独的变量。更妙的是,将所有的模卷放入一个列表中,然后简单地使用count函数来确定每一个的数量。在
相关问题 更多 >
编程相关推荐