Skip to main content
 首页 » 编程设计

python之手动功能对 3 个数字进行排序,从最低到最高

2024年11月24日9kerrycode

因此,对于我的家庭作业问题,我必须使用 3 个函数来创建 sort() 函数的手动版本:moreThan()、swap() 和 sort3()。 sort3() 显然是调用其他两个的函数。我的问题是 swap 函数在 sort3() 中没有被正确调用,并且从未真正执行过。

我一直在尝试更改 swap() 函数中的值,尝试在元组和列表中列出 swap() 的返回值,但这些都不起作用。

def moreThan(moreOne, moreTwo): 
    if moreOne > moreTwo: 
        return True 
    else: 
        return False 
 
def swap(swapOne, swapTwo): 
    swapOne, swapTwo = swapTwo, swapOne 
    return (swapOne, swapTwo) 
 
def sort3(sortOne, sortTwo, sortThree): 
    if moreThan(sortOne, sortTwo) == True: 
        swap(sortOne, sortTwo) 
        print("swap one worked") 
    if moreThan(sortOne, sortThree) == True: 
        swap(sortOne, sortThree) 
        print("swap two worked") 
    if moreThan(sortTwo, sortThree) == True: 
        swap(sortTwo, sortThree) 
        print("swap three worked") 
    print(sortOne, sortTwo, sortThree) 
sort3(1,3,2) 

预期输出为 1,2,3。然而,实际输出是 1,3,2,就好像这些值根本没有交换一样。

请您参考如下方法:

Python 不允许函数在调用者的命名空间中重新绑定(bind)局部变量。这意味着您的 swap() 调用实际上没有做任何事情。您希望以这种方式调用该函数:

sortOne, sortThree = swap(sortOne, sortThree) 

但在这种情况下,将 this 转换为函数并不能真正提高可读性或可重用性,因此您最好直接内联该函数。

或者,如果您可以更改函数签名并将未排序的数据保存在可变数据结构(如列表)中,您可能希望传递它,因此 swap 变为 swap(list, index1, index2).