Home > Back-end >  Find a sum in n arrays equal to a given value?
Find a sum in n arrays equal to a given value?

Time:06-03

Let's say i have n arrays :

a = [1,2,3,4,5,6]
b = [0,3,5,7,9,10]
c = [3,3,5,6,7,8]
...

How to find a sum in these arrays that equals a given value X ?

I get there when I do this :

for i in a:
    for j in b:
       for k in c:
          if i   j   k == X:
                ...

But it's hard-coded, how to do it with n arrays ?

CodePudding user response:

This will make the product of any number of arrays and print the values whose sum equal a certain value.

import itertools

a = [1,2,3,4,5,6]
b = [0,3,5,7,9,10]
c = [3,3,5,6,7,8]

arrays = [a, b, c]

X = 15

for x in itertools.product(*arrays):
    if sum(x) == X:
        print(" ".join(str(v) for v in x))

CodePudding user response:

You can use recursion with lists joined into single 2D list:

a = [[1,2,3,4,5,6], [0,3,5,7,9,10],[3,3,5,6,7,8]]

def sumof(a, idx, value, lst):
    if value < 0:
        return
    if idx == len(a):
        if (value == 0):
            print(lst)
        return
    for x in a[idx]:
        sumof(a, idx   1, value - x, lst   [x])

sumof(a, 0, 22, [])
  • Related