gpt4 book ai didi

python - 递归Python

转载 作者:行者123 更新时间:2023-11-30 22:42:58 25 4
gpt4 key购买 nike

def removedups(word):
if len(word)<=1:
return word
else:
if word[0]==word[1]:
return removedups(word[1:])
else:
return word[0]+removedups(word[1:])

print(removedups('aabbcc'))

我不明白在这种情况下递归是如何工作的。到目前为止我的知识是:

1)它跳过基本测试

2) 进入递归调用并返回'abbcc',然后重新开始:

3) 递归调用中的 if 语句为 false,因此您可以忽略它

4) else 语句是我感到困惑的地方,因为它说 return word[0] +removedups(word[1:])。它是否执行 if 语句并检查单词('bbcc')

最佳答案

return word[0]+removedups(word[1:])

仅当removedups(word[1:])执行完成时,才会返回word[0]+removedups(word[1:])。

removedups('bbcc') 返回'bc'

因此,removedups('abbcc') 返回 'a' + 'bc',即 'abc'

关于python - 递归Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41947785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com