【发布时间】:2021-12-31 22:17:39
【问题描述】:
我对编程比较陌生,对 Python 完全陌生。 我目前正在练习递归函数。
我试图实现一个简单的排序函数,它递归地搜索给定列表的最小值并将其附加到新列表中。
但是,当返回列表时,它只返回列表的最后一个(最高)值。
最让我困惑的是,如果我在返回结果之前放一个print(result),该函数会打印整个排序列表。
这是我的代码。
PS:函数smallesListIndex() 搜索给定列表的最小值的索引。
功能:
def recSort(liste, result=None):
listIn = liste
length = len(liste)
smallestIndex = smallestListIndex(listIn)
# To prevent creating a new list in every recursion, an intermediate list is to be created.
if result is None:
result = []
if length == 1:
result.append(listIn[smallestIndex])
print(result)
return result
else:
result.append(listIn[smallestIndex])
listIn.pop(smallestIndex)
length -= 1
# the intermediate list is to be given to the next recursion.
return recSort(listIn, result)
主要:
if __name__ == "__main__":
liste = [5, 2, 4, 8, 7, 10, 6]
recSort(liste)
print(liste)
输出:
[2, 4, 5, 6, 7, 8, 10] # Output from the print function
[10] # Output from the main function
【问题讨论】:
-
你返回了排序后的列表,但你从来没有对它做任何事情
liste = recSort(liste) -
哦,原来如此!比我想象的要容易,但这已经困扰了我很长一段时间了!!谢谢