我對編程比較陌生,對 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
uj5u.com熱心網友回復:
您的函式recSort回傳一個串列,在您的示例中,您不使用它。
嘗試,看看結果:
if __name__ == "__main__":
liste = [5, 2, 4, 8, 7, 10, 6]
res = recSort(liste)
print(res)
解釋一下,您的函式修改了輸入串列。這就是為什么你只能得到一個值。
如果你不想修改你的輸入,你可以listIn = liste[:]在你的函式中嘗試。
uj5u.com熱心網友回復:
- 你的串列
liste是不一樣的,因為沒有使用copy函式,你只是在創建參考,所以無論你對參考做什么,你都是對原始串列做的。 - 您正在從
recSort函式中回傳內容,但并未將它們保存在任何地方。你可以在main類似的東西中使用result = recSort(liste)然后print(result)。
uj5u.com熱心網友回復:
如果不是print(liste)你這樣做,print(recSort(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))
輸出:
[2, 4, 5, 6, 7, 8, 10]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/363647.html
下一篇:F#int串列與單位串列
