【问题标题】:Basic recursion on string?字符串的基本递归?
【发布时间】:2016-06-25 17:46:02
【问题描述】:

我想要一个程序,只通过递归和 if-else 子句以这种方式打印一个单词:

P

派特
皮斯
毕索
蟒蛇

为什么下面的代码不起作用?它给了我一个超出最大递归深度的错误。

def oneToAll (word, x):
    if -x < 0:
        print(word[:-x])
        oneToAll(word, x+1)
    else:
        return

wordOutside = "Python"
oneToAll(wordOutside, len(wordOutside))

【问题讨论】:

  • 当你递归时你不想x - 1而不是x + 1吗?
  • 对字符串进行递归很棘手,因为您可以遍历一个空字符串...
  • @jonrsharpe -- OP 并没有真正迭代字符串。递归实际上是向下传递一个索引。这可能不是在 python 中进行递归的典型方法,但我认为这对于这个问题是有意义的,因为 op 想要打印 'P' before 'Py'
  • 你有无限递归,因为非空字符串的长度总是正数,因为你的递归情况总是增加 x,因此-x 总是小于 0
  • 你为什么用-x &lt; 0而不是简单的x &gt; 0

标签: python string recursion


【解决方案1】:
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 子句(试一试!)。

【讨论】:

    【解决方案2】:

    我可能遗漏了一些东西,但你可以像这样实现同样的事情:

    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] 是一个空字符串,因此您需要单独处理这种情况。

    【讨论】:

      【解决方案3】:

      用直观的“单词”索引试试这段代码

      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))
      

      【讨论】:

        猜你喜欢
        • 2021-08-21
        • 1970-01-01
        • 2013-04-06
        • 2017-10-28
        • 1970-01-01
        • 2020-03-23
        • 2023-03-08
        • 1970-01-01
        • 2023-01-11
        相关资源
        最近更新 更多