[英]find the general case of while loops
我正在使用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
等等,我想做的就是找到一种方法来为任何数量的元素的任何列表实现此代码(一般情况),但是我无法找出如何将这些while循环转换为任意数量的dimesion(数字数组中的元素数)
以防万一此代码将执行以下操作:
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
任何帮助将非常感激
我同意这些意见,几乎可以肯定有一种更好的方法。 但是,此递归函数(快速将其卡在一起)将执行此操作并在适当位置编辑数组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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.