1

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 ?

3
  • a+b+c has no sense - it will concatenate the lists. Commented Jun 3, 2022 at 9:19
  • So what do you want? those numbers or a true/false answer? also do you have like negative numbers there? Commented Jun 3, 2022 at 9:21
  • 1
    what do you mean by "find a sum". What do you want to do, what output do you want to get, what conditions are there? Commented Jun 3, 2022 at 9:21

2 Answers 2

1

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, [])
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.