Suppose I have an array A. I have a series of index pairs (a1, b1), (a2, b2) ... (an, bn)
I want to obtain all the sums of the elements between those pairs. i.e.
If you have a lot of index pairs and your array is long then caching might be an option. I'd try a recursive approach like
CACHE = {}
def mysum(a, b):
if (a, b) in CACHE:
return CACHE[(a, b)]
if a >= b:
return 0
s = A[a] + mysum(a+1, b)
CACHE[(a, b)] = s
return s
Not checked for correctness or efficiency, though. Decreasing the upper index b could be used as well.