[英]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.