UnboundLocalError:分配前已引用局部变量“ cnt”

时间:2019-01-13 07:37:00

标签: python python-3.x

class Solution:
    def subarraysDivByK(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        l = len(A)
        div = [[0 for col in range(l)] for row in range(l)]
        sums = [[None for col in range(l)] for row in range(l)]
        global cnt
        cnt = 0
        for i in range(l):
            if A[i]%K == 0:
                div[i][i] = 1
                cnt = cnt+1

        def impl(self,st,en):
            print(st,en)
            if sums[st][en]!=None:
                return sums[st][en]

            if A[st] == A[en]:
                if A[st]%K == 0:
                    sums[st][st] = A[st]
                    div[st][st] = 1
                    print(st,en,sums[st][en])
                    if sums[st][en]%k == 0:
                        div[st][en] = 1
                        cnt = cnt+1
                    return sums[st][st]
            elif st+1==en:
                sums[st][en] = A[st]+A[en]
                print(st,en,sums[st][en])
                if sums[st][en]%K == 0:
                    div[st][en] = 1
                    cnt = cnt+1
                return sums[st][en]
            else:
                if sums[st+1][en]==None:
                    sums[st][en] = impl(self,st+1,en)+A[st]
                if sums[st][en-1]==None:
                    sums[st][en] = impl(self,st,en-1)+A[en]
                #sums[st][en] = sums[st+1][en]+ A[st]
                print(st,en,sums[st][en])
                if sums[st][en]%K == 0:
                    div[st][en] = 1  
                    cnt = cnt+1
                return sums[st][en]


        impl(self,0,len(A)-1)
        print(cnt)
        #print(sums)

1 个答案:

答案 0 :(得分:0)

您应该在函数global cnt中添加impl,以便全局变量可见。

def impl(self,st,en):
    global cnt
    ...

有关更多信息,请检查:enter link description here