python: recursive check to determine whether string is a palindrome

前端 未结 6 1325
死守一世寂寞
死守一世寂寞 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:26

    def is_palindrome(s):
        if not s:
            return True
        else:
            return s[0]==s[-1] and is_palindrome(s[1:-1])
    

    or, if you want a one-liner:

    def is_palindrome(s):
        return (not s) or (s[0]==s[-1] and is_palindrome(s[1:-1]))
    

    Hope that helps

提交回复
热议问题