I am currently working with a few mathematical problems. Some involve double summations while others involve double products. Some include a combination summation with a product.
Python permits double summation in a single line of code. Take the example:
This can be simply solved with a single code line:
>>> sum((x + y) for y in range(1,4) for x in range(1,3))
21
Similarly, double products can be calculated with a single line of code. Example:
And the coded solution using Python 3.8:
>>> import math
>>> math.prod((x + y) for y in range(1,4) for x in range(1,3))
1440
How can I complete a similar problem that includes a single summation and a single product? Is it possible using a single line of code? For example:
I thought this may be as simple as:
>>> sum((math.prod(x + y)) for y in range(1,4) for x in range(1,3))
TypeError: 'int' object is not iterable
but print(dir(sum)) and print(dir(math.prod)) show the magic method __iter__ is absent from both sum and math.prod, hence the TypeError.
I know I can use a for loop like this:
>>> ans = 0
>>> for x in range(1,3):
... ans += math.prod((x + y) for y in range(1,4))
>>> ans
84
but this gets a little untidy when I have more summations and products in the same equation (up to four, occasionally more).
Is there a simple single code line approach for combining summations and products I’m missing? Or is the for loop method the only way? Any thoughts?