anon
anon

Reputation:

Fastest way to sum values every combination of multiple lists in Python

I have 5 lists that contain some data:

a = [52, 265, 1, 98, 26]
b = [42, 85, 45, 2, 3, 8, 632]
c = [7, 731, 92, 65, 28, 62]
d = [3, 5, 44, 55]
e = [15, 35, 850, 6, 18, 41]

What I want to do is get the sum of the values of every possible combination, for example:

a[0] + b[0] + c[0] + d[0] + e[0] = **121**
...
a[4] + b[6] + c[5] + d[3] + e[5] = **816**

This needs to be done is the fastest way possible, because in my code the length of these lists is bigger, thus making the calculation of all possibilities extremely time demanding.

My first idea was using nested for loops, but that's not fast enough. I imagine some transformations and some magic could be done with NumPy to speed up this process.

Upvotes: 0

Views: 2044

Answers (2)

Aaditya Ura
Aaditya Ura

Reputation: 12679

You want something like this ?

a = [52, 265, 1, 98, 26]
b = [42, 85, 45, 2, 3, 8, 632]
c = [7, 731, 92, 65, 28, 62]
d = [3, 5, 44, 55]
e = [15, 35, 850, 6, 18, 41]

import itertools

print(list(map(lambda x:sum(x),itertools.product(a,b,c,d,e))))

output:

119, 139, 954, 110, 122, 145, 121, 141, 956, 112, 124, 147, 160, 180, 995, 151, 163, 186, 171, 191, 1006, 162, 174, 197, 843, 863, 1678, 834, 846, 869, 845, 865, 1680, 836, 848, 871, 884, 904, 1719, 875, 887, 910, 895, 915, 1730, 886, 898, 921, 204, 224, 1039, 195, 207, 230, 206, 226, 1041, 197, 209, 232, 245, 265, 1080, 236, 248, 271, 256, 276, 1091, 247, 259, 282, 177, 197, 1012, 168, 180, 203, 179, 199, 1014, 170, 182, 205, 218, 238, 1053, 209, 221, 244, 229, ....

Upvotes: 0

Joran Beasley
Joran Beasley

Reputation: 114038

the fastest way to actually sum all the combinations(you actually want the product, not the combinations) is to generate them and sum them

print([(x,sum(x)) for x in itertools.product(my_list1,my_list2,my_list3,...)])

but I suspect that the secret is to not check all the products, but instead to intelligently select specific values to narrow your search space

Upvotes: 1

Related Questions