當寫東西遞歸我試着想兩件事情
- 的條件來停止遞歸
- 我想要的一個迭代做的,我怎麼能傳遞前進到下一個迭代。
另外我建議讓一個迭代工作,然後擔心再次調用自己。否則,它可能難以調試
反正所以將其應用到你的邏輯
- 當輸出字符串的長度的輸入字符串的長度相匹配
- 加一個字母以相反的新名單。維持至今累計本身
我想只需要修改你的代碼略有我認爲這會幫助你學習最...但有一個困難時期與進步通列表,所以我試着寫我會如何處理你的邏輯。 希望你仍然可以從這個例子中學到一些東西。
def reverse_string(input_string, output_list=[]):
# condition to keep going, lengths don't match we still have work to do otherwise output result
if len(output_list) < len(list(input_string)):
# lets see how much we have done so far.
# use the length of current new list as a way to get current character we are on
# as we are reversing it we need to take the length of the string minus the current character we are on
# because lists are zero indexed and strings aren't we need to minus 1 from the string length
character_index = len(input_string)-1 - len(output_list)
# then add it to our output list
output_list.append(input_string[character_index])
# output_list is our progress so far pass it to the next iteration
return reverse_string(input_string, output_list)
else:
# combine the output list back into string when we are all done
return ''.join(output_list)
if __name__ == '__main__':
print(reverse_string('hello'))
這是遞歸的樣子此代碼
1.
character_index = 5-1 - 0
character_index is set to 4
output_list so far = ['o']
reverse_string('hello', ['o'])
2.
character_index = 5-1 - 1
character_index is set to 3
output_list so far = ['o', 'l']
reverse_string('hello', ['o', 'l'])
3.
character_index = 5-1 - 2
character_index is set to 2
output_list so far = ['o', 'l', 'l']
reverse_string('hello', ['o', 'l', 'l'])
4.
character_index = 5-1 - 3
character_index is set to 1
output_list so far = ['o', 'l', 'l', 'e']
reverse_string('hello', ['o', 'l', 'l', 'e'])
5.
character_index = 5-1 - 4
character_index is set to 0
output_list so far = ['o', 'l', 'l', 'e', 'h']
reverse_string('hello', ['o', 'l', 'l', 'e', 'h'])
6. lengths match just print what we have!
olleh
這看起來並不像有效的Python函數的定義。 if語句在底部附近是否存在格式問題? –
您不能將字母放在空字符串中;字符串是不可變的。當函數返回時,對參數所做的任何更改都會隨着該(本地)變量而消失。 – chepner