Search code examples
pythonvariablestreecycle

an unknown number of cycles


If n=1 I want to write:

for a1 in range(-10,10,1):
    if 13*a1 == 1:
        print('Success')

if n=2 I want to write:

for a1 in range(-10,10,1):
    for a2 in range(-10,10,1):
        if 13*a1+27*a2==1:
            print('Success')

if n=3 I want to write:

for a1 in range(-10,10,1):
    for a2 in range(-10,10,1):
        for a3 in range(-10,10,1):
            if 13*a1+27*a2+37*a3==1:
                print('Success')

etc. n can be 1 or 2 or 3 .. 20. n is a random number from 1 to 20 How can I write the next code:

for a1 in range(-10, 10, 1):
    for a2 in range(-10,10,1):
     ....
        for an in range(-10,10,1): #n is a random number from 1 to 20
            if some_number_1*a1+...+some_number_n*an == 1:
                print('Success')

My attempt to find a solution:

  1. Maybe we can use recursion

    def recur(a):
       for a in range(-10,10,1):
          recur(a)
    

    this method will not work

  2. Maybe we can use lists. For example,

     list[1]=-10,..., 10
     list[2]=-10,...,10
      ...
     list[n]=-10,...,10
    

    So we have matrix(n,21). But I don't see how I can use this matrix to solve my problem.

  3. Maybe we need to use trees but I've never worked with them

  4. Maybe I can use a library to solve the equation a1*x1+a2*x2+...+an*xn=1 but it's not interesting. I want to know how I can solve this task myself.


Solution

  • Use itertools.product:

    def func(a):
        for i in itertools.product(range(-10, 10), repeat=len(a)):
            if sum(x*y for x, y in zip(i, a)) == 1:
                print("success")