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
Joseph Farah
  • 2,463
  • 2
  • 25
  • 36
  • 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]` – NightShadeQueen Sep 24 '15 at 02:09

2 Answers2

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

Remi Guan
  • 21,506
  • 17
  • 64
  • 87
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

Community
  • 1
  • 1
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80