我有代碼嘗試使用Python從列表中反轉字符串,並且無法使用傳統方法作爲練習的一部分(我不能在迭代時更改列表,但我必須遞歸執行)但我的函數沒有返回我的字符串,不知道這個問題可能是什麼:從列表中返回一個字符串
list1 = []
def reverse(text):
note = ''
for x in text:
list1.append(x)
print list1
# for x in list1:
# note = note+list1.pop()
def recursive(toRev):
if not list1:
print toRev, 'Last toRev'
return toRev
else:
toRev = toRev+list1.pop()
recursive(toRev)
print toRev, 'Note with in the loop'
#recursive(toRev)
finalvar = recursive(note)
print finalvar, ' :Final'
return finalvar
reverse('Python!')
你能解釋一下你更好正在試圖做的,(我認爲)轉讓的參數是什麼呢?如果目標是'reverse'('Hello')'返回''olleH'',那麼根本不需要列表或遞歸。您可以使用切片或多次記錄在SO中的內置「反轉」功能來完成此操作。 –
@ Two-BitAlchemist讓學生用遞歸編寫自己的反轉函數是一個相當常見的練習。 OP在問題中提到他們不允許使用內置方法。 –
謝謝仙人掌! – guyinaboxshell