I want to write a code (in python 3) that is able to calculate the sum of all possible combinations of a varying number of lists. The result of the sum needs to be checked with a specified value. For all combinations where the sum adds up to the specified value, I would like to create a new list containing just those values.
For example:
value = 5
a = [1, 2, 3, 4]
b = [2, 3, 4, 5]
1 + 2 = 3 - x
1 + 3 = 4 - x
1 + 4 = 5 - correct
1 + 5 = 6 - x
2 + 2 = 4 - x
2 + 3 = 5 - correct
...
The result should be for example:
res = [[1, 4], [2, 3], [3, 2], [4, 1]]
I know that a simple option would be to use nested for-loops. The problem is that at the time of writing the code I dont know how many lists there will be, resulting in the need to define all possible cases. This is something I dont want to do. By the time I am running the code, I do know how many lists there are. The length of the lists will always be the same (26 elements).
The lists that need to be checked are stored in a list in the following way. For example:
list = [[1, 2, 3, 4], [2, 3, 4, 5]]
An example of an actual set of lists that I would like to solve this problem for is:
list = [[0, 2, 0, 0, 5, 0, 0, 8, 0, 0, 11, 0, 0, 14, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 2, 0, 0, 5, 0, 0, 8, 0, 0, 11, 0, 0, 14, 0, 0, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
All the zero values are the result of other refinements in the total number of options that do not meet other criterias.
I hope someone can push me into the right direction. Thanks in advance!
itertools.product.res = [[1, 4], [2, 3], [3, 2]], since there's no 1 in listb.comprehensions, forlistorsetto help build your results, they support anifclause which would help filter out the results to the ones you want.