我希望有一个程序,它只通过递归和if-else子句以这种方式打印我的单词:
P Py Pyt 皮斯 毕索 Python
为什么下面的代码不工作?它给了我一个超过最大递归深度的错误。
def oneToAll (word, x):
if -x < 0:
print(word[:-x])
oneToAll(word, x+1)
else:
return
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))发布于 2016-03-10 18:12:42
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子句(尝试一下!)。
发布于 2016-03-10 18:29:07
我可能错过了什么,但你也可以做到这样:
def one_to_all(w):
if w:
one_to_all(w[:-1])
print w
one_to_all('Python')您的代码不能工作,因为(i)您将1加到x,而不是减去1和(ii)当x达到零时,word[:-x]是一个空字符串,因此您需要分别处理这种情况。
发布于 2016-03-10 22:53:32
使用直观的"word“索引来尝试这段代码
def oneToAll(word, x):
if x > 1:
print (word[0:len(word) - x])
oneToAll(word, x - 1)
elif x == 1:
print (word)
wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))https://stackoverflow.com/questions/35923991
复制相似问题