为什么我不能在Python的递归函数中包含变量

时间:2016-05-17 09:15:58

标签: python python-3.x recursion

它是一个在列表中计算反转并返回计数的函数。

def count_inversion(sequence):
    count = 0

    def merge_count_inversion(L):
        if len(L) > 1:
            # split them.
            mid = len(L) // 2
            leftL = L[:mid]
            rightL = L[mid:]

            merge_count_inversion(leftL)
            merge_count_inversion(rightL)

            # merge them.
            i = j = k = 0
            while i < len(leftL) and j < len(rightL):
                if leftL[i] < rightL[j]:
                    L[k] = leftL[i]
                    i += 1
                else:# no equal situation.
                    L[k] = rightL[j]
                    j += 1
                    count+=j
                k += 1
            while i < len(leftL):#all right is inversion.
                count+=j
                L[k] = leftL[i]
                i += 1
                k += 1
            while j < len(rightL):
                L[k] = rightL[j]
                j += 1
                k += 1

    merge_count_inversion(list(sequence))

    return count

我使用封闭计数,我希望它可以保存所有合并进程的总数。但是,它将是一个局部变量。

  

UnboundLocalError:局部变量&#39; count&#39;在分配前引用

我想我失去了一些递归的概念和python的变量范围。请告诉我我错在哪里以及如何解决它?

提前谢谢。

1 个答案:

答案 0 :(得分:1)

该消息表示client_id= < id of the Client> 不是count的本地变量,您使用的是merge_count_inversion。您应该在函数count += j中移动count = 0

merge_count_inversion

使用 Python 3

def count_inversion(sequence):

    def merge_count_inversion(L):
        count = 0
        if len(L) > 1:
            # split them.
            mid = len(L) // 2
            leftL = L[:mid]
            rightL = L[mid:]

            merge_count_inversion(leftL)
            merge_count_inversion(rightL)

            # merge them.
            i = j = k = 0
            while i < len(leftL) and j < len(rightL):
                if leftL[i] < rightL[j]:
                    L[k] = leftL[i]
                    i += 1
                else:# no equal situation.
                    L[k] = rightL[j]
                    j += 1
                    count+=j
                k += 1
            while i < len(leftL):#all right is inversion.
                count+=j
                L[k] = leftL[i]
                i += 1
                k += 1
            while j < len(rightL):
                L[k] = rightL[j]
                j += 1
                k += 1

    count = merge_count_inversion(list(sequence))

    return count