我需要来自不在 Python 列表中的 for 循环的数字总和

I need the sum of numbers from a for-loop that is NOT in a list in Python

我在返回总和时遇到问题。我一直为零。

为了更好地理解,我对打印结果进行了评论。同样,我的代码返回 0,而不是 11。


A = [1, 5, 2, 1, 4, 0]

def solution(A):

    start = [i - j for i, j in enumerate(A)]

    start.sort()     #[-4, -1, 0, 0, 2, 5]

    for i in range(0, len(A)):
        pair = 0

        end = i + A[i]   #1, 6, 4, 4, 8, 5 

        count = bisect_right(start, end)     #4, 6, 5, 5, 6, 6

        count_1 = count-1        #3, 5, 4, 4, 5, 5
        count_2 = count_1 - i    #3, 4, 2, 1, 1, 0
        pair += count_2          #???????  I need the above added together like this 3+4+2+1+1+0 since 
                                           that's the answer.

    return pair

print(solution(A))

正如您在评论中所写,最后一个 count2 为零。

你将零加到零,循环结束,你 return 为零。

你需要在循环外启动计数器,或者你也可以在循环外求和,像这样

counts = []
for i, x in enumerate(A):
   counts.append(bisect_right(start, i + x) - 1 - i) 
return sum(counts)

可以重写

return sum(bisect_right(start, i + x) - 1 - i for for i, x in enumerate(A))