简体   繁体   中英

find the general case of while loops

I am working with a python list as the following code:

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

But for a bigger list for example:

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

and so on What I am trying to to do is to find a way to implement this code for any list of any number of element (the general case) But I cannot find out how to transform these while loops to any number of dimesnions (number of elements in the array)

and just in case this code will do the following:

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

Any help would be much appreciated

I agree with the comments, there's almost certainly a better way to do this. However, this (quickly chucked together) recursive function will do it and edit your array x in place

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM