Numpy sum of values in subarrays between pairs of indices

后端 未结 4 1957
情书的邮戳
情书的邮戳 2020-12-21 03:58

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.

4条回答
  •  被撕碎了的回忆
    2020-12-21 04:49

    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.

提交回复
热议问题