python - 字符串的基本递归?

标签 python string recursion

我想要一个程序,仅通过递归和 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/

相关文章:

python - Pandas groupby 将 ndarrays 的嵌套数组分配回数据帧

python - Recaman 递归

java - 在 Java 中使用 BigInteger 递归生成 Lucas 系列

javascript - 需要有关 JavaScript 递归和异步方法的建议

Python 按键错误

python : efficient bytearray incrementation

python - 在 python 中加密

java - 逐行解析文本文件,跳过某些行

python - Django 从 _meta.get_field 添加多对多关系

string - 如何在 slice 中写入函数的结果