为什么我不能在Python的递归函数中获取封闭变量

2024-09-26 22:55:17 发布

您现在位置:Python中文网/ 问答频道 /正文

它是一个函数,用于计算列表中的倒数并返回计数。你知道吗

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: local variable 'count' referenced before assignment

我想我失去了一些递归和python变量范围的概念。请告诉我哪里错了,怎么解决?你知道吗

先谢谢你。你知道吗


Tags: 函数列表lenifdefcountmergeinversion
1条回答
网友
1楼 · 发布于 2024-09-26 22:55:17

这个消息意味着count不是merge_count_inversion的局部变量,您在这里使用了count += j。您应该在函数merge_count_inversion中移动count = 0。你知道吗

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

使用Python 3

def count_inversion(sequence):
    count = 0    
    def merge_count_inversion(L):
        nonlocal count
        if len(L) > 1:
        ......

    merge_count_inversion(list(sequence))

    return count

相关问题 更多 >

    热门问题