[英]Lite empty on return from function in python
問題是為什么變量測試為空? 程序將返回正確排序的數組。 但似乎沒有得到分配。
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)
這將返回以下內容。
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
您忘記了第一個條件的回報:
if sort == True:
return my_sort(array_to_sort)
同樣,您也不需要將布爾值與布爾值進行比較。 您的代碼應如下所示:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.