user2240288
user2240288

Reputation: 235

Python: Checking for palindrome returns False for some reason

I'm trying to write a program, and one of the things I need to do is to check if a number is a palindrome. For some reason, what I wrote does not work:

flag = True
for j in range(0, len(listnum)):
    for t in range(len(listnum) -1, -1, -1):
        if listnum[j] == listnum[t]:
            flag = True
            print "false"
         else:
            flag = False
            print "false"
            break
if flag == True:
    return True
else:
    return False

The print "false"/"true" part is for debugging. I took this code out of a function I wrote, which is why it says "return True/False".

The number I'm checking is 906609

Upvotes: 0

Views: 302

Answers (3)

Thijs van Dien
Thijs van Dien

Reputation: 6616

It's not an answer to why your code doesn't work, but you might be interested to know that there's a much easier way to determine whether a word is a palindrome. By definition, a palindrome is a word that is not changed by reversing it. Hence:

def is_palindrome(word):
    return word == ''.join(reversed(word))

print is_palindrome('906609') # True

The only part of this that may require explanation is the joining. It is necessary because reversed returns the letters of the word one by one, so you first need to put them together again.

As pointed out in a comment, another way of writing it is word == word[::-1]. It means exactly the same, but is arguably a bit more cryptic.

Upvotes: 2

propeller
propeller

Reputation: 385

Your function checks if the last number is different from any other in the list. What you want is probably:

def palindrome(listnum):
    for j in range(0, len(listnum)):
        t = len(listnum) - j - 1
        if listnum[j] != listnum[t]:
            return False            

    return True

assert palindrome([9,0,6,6,0,9])
assert palindrome("ABBA")
assert palindrome([])
assert palindrome("1")
assert palindrome([1.0, 2, 1])
assert not palindrome("lolz")
assert not palindrome([1,2,3])

Upvotes: 1

Tom Dalton
Tom Dalton

Reputation: 6190

The main problem here is the nesting of the for loops. It looks like you want to update j and t in lock-step, but instead you're starting with j=0 and then checking all values of t. Then j=1 and you check all values of t again, etc.

Instead of the nested loop, you could use a loop counter to track the distance you're looking into the word and then calculate j and t from that. E.g.

for d in range(len(listnum)/2):
    j = d
    t = len(listnum) - d - 1
    #letter equality check here, return if false

return True

Upvotes: 2

Related Questions