0

I've just started Python and need to write a program that tells if a string is a palindrome. Here is what I have so far.

def palp(word):
    if len(word) < 2:
        return True
    left_index =  (0)
    right_index = len(word) - 1
    while len(left_index) <> len(right_index):
        return False
    if left_index == right_index:
        left_index + 1
        right_index - 1
        return True

I don't know but for some reason it doesn't return true for any palindrome except for ones with only one letter.

Edited by peter_budo: Code need to be between code tags not out of them

4
Contributors
4
Replies
6
Views
6 Years
Discussion Span
Last Post by snippsat
0

You can not take len of integer values, wouldn't you need to check letters in word? You also forgot CODE tags.

Edited by happygeek: fixed formatting

1

Unnecessary complicated, but forgetting case of word differences.

This simple version, which does not deal with palindromic sentences:

def palindromic(s):
    s = s.lower()
    return s == s[::-1]
>>> palindromic('Saippuakivikauppias')
True
0

As pyTony say you complicated it by use of ternary operator( a if b else c )
One thing also to remember is to remove punctuation.
Here one with translate.

from string import punctuation

def is_palindrom(word):
    word = word.lower().translate(None, punctuation)
    return word == word[::-1]

print is_palindrom('Saippuakivikauppias') #True

And a test with a longer palindromic sentence.

def is_palindrome(s):
    letters = [c for c in s.lower() if c.isalpha()]
    return letters == letters[::-1]

s = '''\
A man, a plan, a canoe, pasta, heros, rajahs, a coloratura, maps, snipe,
percale, macaroni, a gag, a banana bag, a tan, a tag, a banana bag again
(or a camel), a crepe, pins, Spam, a rut, a Rolo, cash, a jar, sore hats,
a peon, a canal ? Panama!'''

print is_palindrome(s) #True

Edited by snippsat: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.