Nika Tvildiani
Nika Tvildiani

Reputation: 47

Algorithm for n-tuple Summation

I am trying to write computer programm for some mathematical formula, in which I came across with n-tuple Summation, by which I mean $ \sum \sum \sum \dddot $. I am searching for efficient algorythm to write code in python. For exapmle: $$ \sum_{j_1}^{a_1} \sum_{j_2}^{a_2} \dddot , \sum_{j_i}^{a_i} f(j_1,j_2, \dddot , , j_i) $$ One method that I can see, is to generate one big list with size probably $ a_1 \dot a_2 \dot \dddot , a_i $ and iterate over it. But i think it is not perfect way and there exist better solution. Number of sums aren't fixed, in other words, numbers of sigma notations in expresion can be any number.

Upvotes: 0

Views: 73

Answers (1)

Dillon Davis
Dillon Davis

Reputation: 7750

Without some insight into what f() does, there isn't much you can do in the way of optimization. You might as well keep your code simple-

from itertools import starmap, product

def calcsum(func, intervals):
    ranges = starmap(range, intervals)
    args = product(*ranges)
    return sum(starmap(func, args))

Upvotes: 2

Related Questions