简体   繁体   English

为什么我的用于检查回文的python算法不起作用?

[英]Why doesn't my python algorithm for checking palindromes work?

So I was doing exercise 6 from chapter 7 from Think Python and it stroke me as odd that this piece of code I wrote as a solution didn't work: 因此,我正在执行Think Python第7章中的练习6,令我感到奇怪的是,我作为解决方案编写的这段代码不起作用:

def is_palindrome(word):
    if len(word) <= 1:
        return True
    elif first(word) == last(word):
        is_palindrome(middle(word))
    else:
        return False

It doesn't enter any recursion and I don't know why. 它不输入任何递归,我也不知道为什么。 It returns None for words longer than 1 character of length. 对于长度超过1个字符的单词,它返回None。 Why is this? 为什么是这样? When the length of the word reaches 1 or less it should return True! 当单词的长度达到1或更短时,它应该返回True! Why doesn't it work? 为什么不起作用?

PS: Here are first, last and middle deffinitions: PS:以下是第一个,最后一个和中间的定义:

def first(word):
    return word[0]

def last(word):
    return word[-1]

def middle(word):
    return word[1:-1]

You're missing a return : 您缺少return

def is_palindrome(word):
    if len(word) <= 1:
        return True
    elif first(word) == last(word):
        return is_palindrome(middle(word))  # <--
    else:
        return False

So your current snippet is returning None once the elif block is entered, since you don't have an explicit return statement there. 因此,一旦输入了elif块,您当前的代码段将返回None ,因为那里没有显式的return语句。 In other words, you do compute is_palindrome(middle(word)) , but you do nothing with the result. 换句话说,您确实要计算is_palindrome(middle(word)) ,但对结果不执行任何操作。

Maybe working through a simple example would help. 也许通过一个简单的例子会有所帮助。 Consider calling the original function with an argument of 'aba' : 考虑使用参数'aba'调用原始函数:

  • function called 函数调用
  • word is now 'aba' word现在是'aba'
  • len(word) <= 1 is False , if -body not entered. if未输入-body, if len(word) <= 1False
  • first(word) == last(word) is True , elif -body entered: first(word) == last(word)Trueelif -body输入:
    • function called recursively: 递归调用的函数:
    • word is now 'b' word现在是'b'
    • len(word) <= 1 is True , if -body entered: len(word) <= 1Trueif输入-body:
      • True returned True返回
  • Return value of recursive call discarded (since we have no return in elif ) 递归调用的返回值被丢弃(因为elif没有return
  • None returned None退货

添加return

return is_palindrome(middle(word))

I think you are missing to return the method in 5th line of your function. 我认为您不希望在函数的第5行中返回该方法。

return is_palindrome(middle(word))

should be there instead of 应该在那里而不是

 is_palindrome(middle(word))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM