[英]Recursive function in Python returns only the last list value
我对编程比较陌生,对 Python 完全陌生。 我目前正在练习递归函数。
我试图实现一个简单的排序 function 递归搜索给定列表的最小值并将其附加到新列表。
但是,在返回列表时,它只返回列表的最后一个(最高)值。
最让我困惑的是,如果我在返回结果之前放置一个print(result)
,function 会打印整个排序列表。
这是我的代码。
PS: function smallesListIndex()
搜索给定列表的最小值的索引。 Function:
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)
Output:
[2, 4, 5, 6, 7, 8, 10] # Output from the print function
[10] # Output from the main function
您的 function recSort
返回一个列表,在您的示例中,您不使用它。
试一试,看看结果:
if __name__ == "__main__":
liste = [5, 2, 4, 8, 7, 10, 6]
res = recSort(liste)
print(res)
为了解释,您的 function 修改了输入列表。 这就是为什么你只能得到一个值。
如果您不想修改您的输入,您可以在 function 中尝试listIn = liste[:]
。
copy
liste
,您只是在创建引用,所以无论您对引用做什么,都对原始列表执行。recSort
function 返回东西,但您没有将它们保存在任何地方。 您可以在main
中使用result = recSort(liste)
然后print(result)
。如果您使用print(recSort(liste))
而不是print(liste)
,那么您的代码就可以工作。
下面完整的更正代码,还添加了我的smallestListIndex()
的简单实现,以实现完整的可运行示例,并重新格式化代码。
def smallestListIndex(l):
return l.index(min(l))
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]
print(recSort(liste))
Output:
[2, 4, 5, 6, 7, 8, 10]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.