python: recursive check to determine whether string is a palindrome

前端 未结 6 1377
死守一世寂寞
死守一世寂寞 2021-01-19 17:11

My task is to define a procedure is_palindrome, that takes as input a string, and returns a boolean indicating if the input string is a palindrome. In this case a single let

6条回答
  •  天命终不由人
    2021-01-19 17:37

    Let's step through your second example, line by line.:

    def is_palindrome(s):
    

    In this case let's let s = "abba", which is the first string you got an error on:

            if s == '':
    

    is evaluated as

            if 'abba' == '':
    

    Which is False, so we skip ahead to else:

            else:
                if (ord(s[0]) - ord(s[len(s)-1])) == 0:
    

    This if statement is equivalent to:

                if (97 - 97) == 0:
    

    It's True, so recursion happens:

                    is_palindrome(s[1:len(s)-1])
    

    or

                    is_palindrome('bb')
    

    Now whatever is the result of this recursion, we ignore it, because the return value is not saved. Thus, when we get to this line:

            return result
    

    We never defined what result was, so Python flips out.

    Other posters already did an excellent job of answering your question. I'm posting to demonstrate the importance of tracing a program to find/fix bugs.

提交回复
热议问题