Home > Blockchain >  Python, Pick numbers, with a given total sum
Python, Pick numbers, with a given total sum

Time:02-05

[[-1, 2, 3], [4, 2, 1], [-2, 6, 4]] For example I have this two dimensional array, and I need to pick the combination of numbers (one from each sublist) that in total give some number, let's say -1, so the right numbers will be -1 from the first, 2 from the second and -2 from the third. What is the fastest and easiest way to do it?

CodePudding user response:

The easiest way would be to use itertools.product but that's not the fastest (it is simple brute force over all possible combinations):

from itertools import product

numbers = [[-1, 2, 3], [4, 2, 1], [-2, 6, 4]]

print(*(p for p in product(*numbers) if sum(p) == -1))
# (-1, 2, -2) 

print(*(p for p in product(*numbers) if sum(p) == 7))
# (-1, 4, 4) (-1, 2, 6) (2, 1, 4)

Getting something faster will require diving into recursion and dynamic programming which will no longer be the simplest way (there's always a trade off)

  •  Tags:  
  • Related