vjg - 8 months ago 39

Python Question

If

`n=1`

`for a1 in range(-10,10,1):`

if 13*a1 == 1:

print('Success')

if

`n=2`

`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`

`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`

`n`

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')

- Maybe we can use recursion

`def recur(a):`

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

recur(a)

this method will not work - 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. - Maybe we need to use trees but I've never worked with them
- Maybe I can use a library to solve the equation but it's not interesting. I want to know how I can solve this task myself.
`a1*x1+a2*x2+...+an*xn=1`

Answer

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")
```

Source (Stackoverflow)