recursion - Python Recursive Function to Check if Palindrome -
this question has answer here:
- how test 1 variable against multiple values? 16 answers
i need define recursive function check if string palindrome.
below's code:
def palindrome_recur(string): if len(string)==0 or 1: return true else: if string[0] == string[-1]: return palindrome_recur(string[1:-2]) else: return false
it passes few test cases, doesn't work string "chipmunks"
. can tell me might have overlooked?
the problem this:
if len(string)==0 or 1:
that checks whether either of len(string) == 0
, or 1
true. since 1
true, whole expression true , function returns true.
you should use
if len(string) <= 1:
instead.
then, you'll find out problem indexing -2 other answers mention.
Comments
Post a Comment