简体   繁体   中英

Determining whether a string is a Palindrome

I wrote the following program to determine whether a string sa 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'  

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.

Your logic is roughly right, but you are missing some things.

  1. The first character in a string is string[0] not string[1] , so you are comparing the wrong characters.

  2. You need to call Palind() as well as def ining it.

  3. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM