0

I'm doing an assignment for an intro course in which I need to determine whether a string is a palindrome. Having trouble with this segment of the code:

    def is_palindrome(letters): 
         if (len(letters))==0:
             return True
         elif len(letters)==1:
             return True
         elif (letters[end])==(letters[0]):
            return is_palindrome(letters[(letters[0+1]):(letters[len(letters)-1])])
         else:
            return False
1
  • 1. I feel like return is_palindrome(letters[(letters[0+1]):(letters[len(letters)-1])]) should be return is_palindrome(letters[1:-1]) . 2. def is_palindrome(letters): return letters == letters[::-1] Commented Sep 24, 2015 at 2:09

2 Answers 2

2

Your code is nearly correct, but you have errors in the slicing of the strings:

def is_palindrome(letters): 
    if (len(letters))==0:
        return True
    elif len(letters)==1:
        return True
    elif (letters[0])==(letters[-1]):       # index [-1] gives the last letter
        return is_palindrome(letters[1:-1]) # slice [1:-1] is the word without the first and last letter.
    else:
        return False

The above works.

I suggest you review this post that explains in details how slicing works: Explain Python's slice notation

Sign up to request clarification or add additional context in comments.

2 Comments

great resource. the link helped out a friend who was struggling with the splicing. +1
@OliverChild-Lanning Now you should accept this answer.
2

Try these following codes:

def palindrome(text):
    if text == text[::-1]:
        print(text, 'is palindrome')
    else:
        print(text, 'is not palindrome')

palindrome('reser')
palindrome('reset')

str[::-1] will reverse the string. for more info, try help(slice).

4 Comments

This is a different method than what the OP tried - of course, it works, but does it teach him to correct his mistake?
@ReblochonMasque Well, I think this way is more clearer and simpler. However you've just post an answer that correct his mistake ;)
Your code as it is returns erroneous answers - please fix it. :)
@ReblochonMasque Finished, I forgot change str[::1] to str[::-1]. Thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.