分而治之 - 获得零和切片的数量

时间:2017-04-26 02:34:24

标签: python-3.x

我对我正在写的一段代码有疑问。这是为了获得数组中加起来为零的切片数。但是,我希望能够使用递归在Python中执行此操作。请看一下我的代码,如果你发现了什么,请告诉我。与迭代方法相比,我得不到正确答案。

def sumzeros(A, low, mid, high):
    leftsum = 0
    rightsum = 0
    counter = 0

    for i in range(low, mid+1):
        leftsum += A[i]

    for j in range(mid+1, high+1):
        rightsum += A[j]

    if leftsum + rightsum == 0:
        counter += 1

    return counter


def solution(A, low, high):
    if low == high:
        if A[low] == 0:
            return 1
        else:
            return 0
    else:
        mid = (low + high) // 2

        left = solution(A, low, mid)
        right = solution(A, mid+1, high)
        cross = sumzeros(A, low, mid, high)

        return cross + left + right

print('Recursive solution: Number of sum zeros = {}'.format(solution(A, 0, len(A) - 1)))

1 个答案:

答案 0 :(得分:0)

使用 mid =(low + high)/ 2 mid = high - (high - low)/ 2