Python: Recursive Check To Determine Whether String Is A Palindrome
Solution 1:
In your first example, you forgot a return statement:
defis_palindrome(s):
if s == '':
returnTrueelse:
if (ord(s[0]) - ord(s[len(s)-1])) == 0:
# v-- forgot this herereturn is_palindrome(s[1:len(s)-1])
else:
returnFalse
Solution 2:
is_palindrome(s[1:len(s)-1])
needs to be...
return is_palindrome(s[1:len(s)-1])
in your first version, or
result = is_palindrome(s[1:len(s)-1])
in your second. Otherwise, you never actually propagate the recursive call's return value back to the original caller.
Solution 3:
# ask user to enter any string
a = raw_input("Enter the string : ")
#palindrome checkprint (a == a[::-1]) and "String is palindrome" or "String is not palindrome"
Solution 4:
Let's step through your second example, line by line.:
defis_palindrome(s):
In this case let's let s = "abba", which is the first string you got an error on:
ifs== '':
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.
Solution 5:
defis_palindrome(s):
ifnot s:
returnTrueelse:
return s[0]==s[-1] and is_palindrome(s[1:-1])
or, if you want a one-liner:
defis_palindrome(s):
return (not s) or (s[0]==s[-1] and is_palindrome(s[1:-1]))
Hope that helps
Post a Comment for "Python: Recursive Check To Determine Whether String Is A Palindrome"