Search code examples
pythonpalindrome

Palindrome program in python


P.S: I'm new to python (and programming in general), however, I've got this question with regards to checking if a word is a palindrome. Here's my code:

def checkPal(word):
    newWord = ""
    for j in range(len(word)-1, 0):
        newWord = newWord + word[j]
        print(newWord) #this doesn't print anything
    if(newWord==word):
        print("Palandrome!!")
    else:
        print("sorry")

So this doesn't throw any errors, however, it doesn't work too! I am aware there are other ways of doing it, like:

str(n) == str(n)[::-1]

This works like a charm. But I'd just like to know what's wrong with my code. I can't seem to find a solution. I've tried item assignments separately too:

Word = ""
toAdd = "LetsTryThis"
Word = Word + toAdd[0]
print(Word)

The output:

L

The output is as expected, but this doesn't seem to work in the for loop of my checkPal function. See comment.

Thanks for the help!


Solution

  • If you want a range in reverse order (initial value greater than final value) you need to specify a negative step (-1 in your case)

    range(5,0)       # doesn't work
    []
    
    range(5,0,-1)    # works
    [5, 4, 3, 2, 1]
    

    But this is an inefficient way of reversing a string, use word[::-1] instead (will be way more efficient)

    if word == word[::-1]:
        print('Palindrome')
    else:
        print('Not a palindrome')
    

    However if word is long, it will take a lot of effort to reverse it and then compare the whole word with the original one.

    Instead you can just iterate once from 0 to len(word)/2 and compare the first element with the last one, the second with the penultimate, etc... Until one of them fail, otherwise it's a palindrome.

    def is_palindrome(word):
        is_palindrome = True
        for i in range(len(word)/2):
            if word[i] != word[-i-1]:
                is_palindrome = False
                break
    
        # you can print if it's a palindrome:
        if is_palindrome:
            print('Palindrome')
        else:
            print('Not a palindrome')
    
        # or just return a boolean answer
        return is_palindrome
    
    # test cases
    is_palindrome('adda')    # even palindrome
    is_palindrome('adfda')   # odd palindrome
    is_palindrome('asda')    # even non-palindrome
    is_palindrome('adfsa')   # odd non-palindrome