0

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!

  • 1
    you can just reverse the string and compare with original string to check palindrome – iamdeowanshi Mar 22 '17 at 16:17
  • 2
    Maybe you meant `for j in range(len(word)-1, -1, -1)`? – nbro Mar 22 '17 at 16:17
  • and I am voting this because this doesn't satisfy stackoverflow standards – iamdeowanshi Mar 22 '17 at 16:17
  • range(len(word) -1, 0) will give a range where the start is greater than the end. So the loop will no execute. You need to use a step of -1 as nbro suggested. – chatton Mar 22 '17 at 16:19
  • wow. Works like a charm! I didn't see anything about passing 3 parameters in range().. I'll try reading a bit more about that. Thanks! – lancev.veigas3 Mar 22 '17 at 16:26
  • Good question here that would be worth a read - http://stackoverflow.com/questions/931092/reverse-a-string-in-python – Craicerjack Mar 22 '17 at 16:30
  • for j in range(len(word)-1,-1,-1) worked well. however, I want to know why my code didn't work. according to what I've written the assignment should create a new string variable with the reverse of the earlier string. Later if the two strings are true, it would show true. What went wrong? – lancev.veigas3 Mar 22 '17 at 16:34

1 Answers1

2

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
  • You also need to be careful about the endpoints, because the correct start and step for the reverse of a given range aren't just the original start and step switched around. `reversed(range(...))` is usually easier to work with. – user2357112 Mar 22 '17 at 16:23
  • "You are building a newWord step by step and then comparing it to the whole word (this will not work)" - that would actually work. I don't see why you think it wouldn't. Maybe you thought the comparison was happening at each step. – user2357112 Mar 22 '17 at 16:34
  • True, he was just reversing the word in the loop. Will correct my answer –  Mar 22 '17 at 16:35
  • Thanks for the help! Learnt quite a few things after raising the question. The alternate solution of comparing the first element with the last one, the second with the penultimate, etc was a great idea.. Thanks. Solved my problem. – lancev.veigas3 Mar 24 '17 at 03:13