我的代碼圖片
我想撰寫一個反轉串列的遞回函式。給定輸入:[1,2,3],函式應回傳 [3,2,1]
但是,我收到此錯誤訊息。
在此處輸入影像描述
uj5u.com熱心網友回復:
試試這樣:
def reverse(lst,start,end):
if start>=end:
return lst
else:
temp=lst[start]
lst[start]=lst[end]
lst[end]=temp
return reverse(lst,start 1,end-1)
l = [1,2,3]
print(reverse(l,0,len(l)-1))
輸出:
[3, 2, 1]
uj5u.com熱心網友回復:
無需任何遞回編程:
list_in = [1, 2, 3]
list_out = list_in[::-1]
uj5u.com熱心網友回復:
newList.append(temp)沒有回傳值,因此回傳 None。newList.append(temp)將 temp 添加到 newList,因此您的代碼可以作為:
def recursiveReverse(dataList):
if len(dataList) == 1:
return dataList
else:
temp = dataList.pop(0)
newList = recursiveReverse(dataList)
newList.append(temp)
return newList
uj5u.com熱心網友回復:
從我在錯誤訊息中看到的內容來看,它正在引發錯誤,您正在嘗試將某些內容附加到 none 型別,如該行中所示return yourlist.append(element)。嘗試先附加到串列,然后將其回傳。像
mylist.append(element)
return mylist
uj5u.com熱心網友回復:
在 python 中,串列是可變物件,list.append它向現有串列添加一個元素但不回傳任何內容。這就是您收到該錯誤的原因。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/461010.html
