【问题标题】:What is wrong with this python code?这个 python 代码有什么问题?
【发布时间】:2019-09-25 23:42:24
【问题描述】:

我想在这里使用递归,但我的代码是错误的。帮助我哪里错了。它只返回 True。我必须返回递归语句以及函数返回 False 的条件。基本上,我想扩展我的代码。

def mypalindrome(l):
  if l==[] or len(l) == 1:
    return(True)
  else:
    return(mypalindrome(l[1:-1]))

【问题讨论】:

  • 因为没有条件返回 false。您必须添加 if 终端条件才能返回 false。

标签: python recursion


【解决方案1】:

你似乎大部分都是对的。您只需要正确调用参数并修复返回值。此外,您缺少检查第一个和最后一个字符的检查,这是一个示例:

string = "reallear"

def mypalindrome(string):
    if len(string) <= 1:
        return True
    elif string[0] == string[-1]:
        return mypalindrome(string[1:-1])
    else:
        return False

print mypalindrome(string)

【讨论】:

    【解决方案2】:

    检查单词回文的几种方法

    def mypalindrome(l):
        if len(l) < 2:
            return True
        if l[0] != l[-1]:
            return False
        return mypalindrome(l[1:-1])
    

    或者更优雅的方式

    def mypalindrome(l):
        return l == l[::-1]
    

    【讨论】:

      【解决方案3】:
      def mypalindrome(l):
        if l==[] or len(l) == 1:
          return(True)
        else:
          return(mypalindrome(l[1:-1]) and l[0] == l[-1])
      

      【讨论】:

      • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的回答添加解释并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-07
      • 2014-08-29
      • 2013-06-05
      相关资源
      最近更新 更多