简体   繁体   中英

Lite empty on return from function in python

Question is why is the variable test empty? The program will return the correctly sorted array. But it does not get assigned it seems.

def my_sort(array_to_sort):
    sort = False
    number_of_items = len(array_to_sort)
    print "sorted array: ", array_to_sort

    for i in range(0, number_of_items-1):
        if array_to_sort[i] > array_to_sort[i+1]:
            tmp = array_to_sort[i]
            array_to_sort[i] = array_to_sort[i+1]
            array_to_sort[i+1] = tmp
            sort = True
    if sort == True:
        my_sort(array_to_sort)
    elif sort == False:
        return array_to_sort

if __name__ == '__main__':
    # main()

    arr = [4,5,7,3,2,1]
    test = my_sort(arr)
    print (test)

This will return the following.

sorted array:  [4, 5, 7, 3, 2, 1]
sorted array:  [4, 5, 3, 2, 1, 7]
sorted array:  [4, 3, 2, 1, 5, 7]
sorted array:  [3, 2, 1, 4, 5, 7]
sorted array:  [2, 1, 3, 4, 5, 7]
sorted array:  [1, 2, 3, 4, 5, 7]
None

You forgot return in your first condition:

if sort == True:
    return my_sort(array_to_sort)

also you don't need to compare boolean value to a boolean value. Your code should look like this:

def my_sort(array_to_sort):
    sort = False
    number_of_items = len(array_to_sort)
    print "sorted array: ", array_to_sort

    for i in range(0, number_of_items-1):
        if array_to_sort[i] > array_to_sort[i+1]:
            tmp = array_to_sort[i]
            array_to_sort[i] = array_to_sort[i+1]
            array_to_sort[i+1] = tmp
            sort = True
    if sort:
        return my_sort(array_to_sort)
    else:
        return array_to_sort

if __name__ == '__main__':
    # main()

    arr = [4,5,7,3,2,1]
    test = my_sort(arr)
    print (test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM