我想要一个程序,仅通过递归和 if-else 子句以这种方式打印出一个单词:
P
Py
Pyt
Pyth
Pytho
Python
为什么下面的代码不起作用?它给我一个超出最大递归深度的错误。
def oneToAll (word, x):
if -x < 0:
print(word[:-x])
oneToAll(word, x+1)
else:
return
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))
最佳答案
def oneToAll (word, x):
if -x < 0:
print(word[:-x])
oneToAll(word, x-1)
elif x == 0:
print(word)
else:
return
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))
这似乎可行。请注意,我现在使用 x-1
而不是 x+1
进行递归,因为您希望 x
始终朝着 努力>0
。
以这种方式实现时,您必须处理 x == 0
的特殊情况。在这种情况下,您想要打印整个字符串,而不是 word[:0]
(它始终是一个空字符串)。另请注意,我没有从 0
分支进一步递归。这是因为在这一点上,你已经完成了。您实际上可以完全删除 else
子句(试一试!)。
关于python - 字符串的基本递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35923991/