M3105 M3105 - 1 month ago 8
Python Question

taking the product of the elements of tuples based on their sum

I would greatly appreciate any feedback regarding the following question. So far I wrote a code on Python that generates the combination of 2 dimensional tuples in which each element is a value from 1 through 4. So for (a1,a2), a1 and a2 can be any value from 1 through 4

Thus this generated the following tuples

tuple_combinations = [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)]


I then took the sum of the elements for each tuple which generated:

sum_tuple_combinations = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8]


Now I need help with computing the product of the elements for tuples whose sum are 5. So for this example that would be the product of tuples (2,3), (3,2) , (1,4) and (4,1) which would give me

[6,6,4,4]


How would I code that on Python?

this is what I've done so far:

import itertools
x = [1,2,3,4]
combinations= [p for p in itertools.product(x, repeat=2)]
print(combinations)
sum_of_combinations = map(sum, combinations)
print(sum_of_combinations)
#product_of_combinations = [x*y for sum_of_combinations = 5]


Moreover, although this solves the 2 dimensional case, where n=2 ,I would like to consider the product of the elements in the tuple for other dimensions such as n=10, n=15 and so on

wim wim
Answer

Don't forget that (1, 4) and (4, 1) also sum to 5.

2-dimensional case:

>>> from itertools import product
>>> L = [1, 2, 3, 4]
>>> [a*b for a,b in product(L, L) if a+b == 5]
[4, 6, 6, 4]

n-dim case:

>>> from operator import mul
>>> n = 2
>>> [reduce(mul, t, 1) for t in product(L, repeat=n) if sum(t) == 5]
[4, 6, 6, 4]