我正在使用python列表作为以下代码:
x=[0.1,0.1,0.1]
dx=0.1
R=1
while x[0] < R:
while x[1] < R:
if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) < R:
x[2] = x[2] + dx
counter = counter + 1
else:
x[1] = x[1] + dx
x[0]= dx
print(counter)
x[0] = x[0] + dx
x[1] = dx
但是对于一个更大的列表例如:
x=[0.1,0.1,0.1,0.1]
dx=0.1
#we have to add another while loop
while x[0]<R:
while x[1]<R:
while x[2]<R:
if np.sqrt(x[0] ** 2 + x[1] ** 2 + x[2] ** 2) < R:
x[3] = x[3] + dx
counter = counter + 1
else:
x[2] = x[2] + dx
x[1]= dx
x[1] = x[1] + dx
x[2] = dx
x[0]=x[0]+dx
x[1]=dx
等等 我想要做的是找到一种方法来为任意数量的元素的任何列表实现此代码(一般情况) 但我无法找到如何将这些循环转换为任意数量的dimesnions(数组中的元素数量)
以防这个代码执行以下操作:
example: for dx=0.1 and R=1 and we start with 0.1
start with x=[0.1, 0.1, 0.1] (after the first loop) x=[0.9, 0.1, 0.1] And then [0.1, 0.2, 0.1] And so on until [0.9, 0.9, 0.1] After we will get [0.1,0.1,0.2] And we will start again with [0.2, 0.1, 0.2] and so on
非常感谢任何帮助
答案 0 :(得分:2)
我同意这些评论,几乎可以肯定这是一种更好的方法。但是,这个(快速放在一起)递归函数会执行它并编辑你的数组x
def f(x, dx, n=0):
if n == len(x) - 2:
while x[n] < R:
if np.sqrt(sum(i**2 for i in x[:-1])) < R: # I think you mean this
x[n+1] += dx
counter += 1
else:
x[n] += dx
x[n-1] = dx
else:
while x[n] < R:
f(x, dx, n+1) # recursion
x[n] += dx
x[n+1] = dx