首页 > 解决方案 > 为什么这个函数不能被调用

问题描述

我有这个列表,我想根据冒泡排序进行排序,并且代码中有一个函数(Swap())拒绝工作。我不知道为什么。有代码

score = [92,95,7,5,85,55,789,47,125,3265,88,965,655,3,15,448,0,255,455]
size = len(score)
x = 0
COMPS = size - 1

def swap():
    temp = score[x + 1]
    score[x + 1] = score[x]
    score[x] = temp

# The Sort Array Function

def SortArray():
    y = 0
    while y < COMPS:
        x = 0 
        while x < COMPS:
            if score[x] > score[x + 1]:
                #This function not working.
                swap()
            x += 1
        y += 1

 #Display Array Function

def displayArray():
    x = 0
    while x < size:
        print(score[x])
        x += 1

SortArray()
displayArray()

但是插入swap()代码,因此是swap()下的代码,并将其替换在SortArray()下,在if 条件下;像这样:

def SortArray():
    y = 0
    while y < COMPS:
        x = 0 
        while x < COMPS:
            if score[x] > score[x + 1]:

                #This Works
                temp = score[x + 1]
                score[x + 1] = score[x]
                score[x] = temp

            x += 1
        y += 1

然后它起作用了,所以我想知道为什么在SortArray()下没有调用swap()函数

标签: python-3.xfunctionbubble-sort

解决方案


我想知道为什么在SortArray()下没有调用swap()函数

实际上,它被调用了——你可以自己print()在其中添加几个调用或使用步进调试器来检查它——但它并没有做你认为它应该做的事情,因为你混淆了局部变量和全局变量。

SortArray()您定义一个名为的局部变量x(它被定义为局部变量,因为您在函数中分配它),这显然是您希望swap()使用的变量。但是在您的swap函数中,您使用的变量x既不是函数的参数,也不是在函数内分配的变量(两者都会使其成为局部变量),因此它被解析为上面声明的全局 x变量。

IOW,swap使用全局,x为什么你希望它使用本地的SortArray()。这也是第二个版本起作用的原因,因为这一次它使用了正确的变量。

解决方案是删除全局x并明确地将正确的值传递给swap(),即:

def swap(x):
    temp = score[x + 1]
    score[x + 1] = score[x]
    score[x] = temp

def SortArray():
    y = 0
    while y < COMPS:
        x = 0 
        while x < COMPS:
            if score[x] > score[x + 1]:
                swap(x)
            x += 1
        y += 1

当你这样做的时候,你也应该这样做score——实际上,你应该尽可能地避免使用全局变量(相信我,你可以在不使用全局变量的情况下编写很多代码):

def swap(score, x):
    temp = score[x + 1]
    score[x + 1] = score[x]
    score[x] = temp

def SortArray(score):
    comps = len(score) - 1
    y = 0
    while y < comps:
        x = 0 
        while x < comps:
            if score[x] > score[x + 1]:
                swap(score, x)
            x += 1
        y += 1


def displayArray(score):
    x = 0
    while x < len(score):
        print(score[x])
        x += 1

if __name__ == "__main__":
    score = [92,95,7,5,85,55,789,47,125,3265,88,965,655,3,15,448,0,255,455]
    SortArray(score)
    displayArray(score)

现在您的函数可以与任何列表或序列一起使用。它们仍然完全不符合 Python 标准,但这显然不是重点(无论如何,Python 内置了最优化的排序算法之一)。


推荐阅读