Reputation: 49
I wrote the following program to determine whether a string s a palindrome using recursion. My problem is that I am not sure how to add a print statement that tells me whether the string is a palindrome or not. I realize that there are other codes which do the same thing, but I am trying to understand if my reasoning is correct.
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring =newstring.lower()
def Palind(newstring):
if newstring[0] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
if s_remain == '':
return True
elif len(s_remain) == 1 :
return True
else:
return Palind(s_remain)
if Palind(newstring):
print 'Yes'
else:
print 'No'
Upvotes: 0
Views: 283
Reputation: 29048
Your logic is roughly right, but you are missing some things.
The first character in a string is string[0]
not string[1]
, so you are comparing the wrong characters.
You need to call Palind() as well as def
ining it.
If you correct those problems, you are taking one letter off each side of the string each time, it gets shorter and shorter - the next interesting thing that happens is you either get down to a single character or you run out of characters. You should be looking for that state.
Upvotes: 1
Reputation: 103555
First, correctly indent your code, and properly lowercase the input:
import re
s= raw_input( " Enter a string to check if it is a palindrome ")
newstring = re.sub('\W', '', s)
newstring = newstring.lower()
def Palind(newstring):
if newstring[1] != newstring[-1]:
#print 'The given string is not a palindrome'
return False
else:
s_remain = newstring[1:-1]
return Palind(s_remain)
Then actually call your function and deal with the result:
if Palind(newstring):
print ('Yes')
else:
print ('No')
That's how you print the result of your function..
You will have problems when you enter a palindrome though, because you never actually return true. You'll need to fix that by checking if you've gotten to the end of the string without returning false.
Upvotes: 1