Tyler Beckler
Tyler Beckler

Reputation: 51

Checking if a number is palindrome

I have this code for checking if a number is a palindrome and for some reason it returns false for number=1 even though it is palindrome. Why is that? The code works for other cases such as 12321.

def palindrome_integer(number): 

    if number != int:
        return False
    elif str(number) == str(number)[::-1]:
        return True
    else:
        return False

Upvotes: 0

Views: 184

Answers (4)

Parnab Dutta
Parnab Dutta

Reputation: 31

solution without string

def palindrome_integer(num):
    copy = num
    rev = 0
    while num!= 0:
        rev = rev*10+num%10
        num = num//10
    return rev == copy

Upvotes: 1

Samudra Ganguly
Samudra Ganguly

Reputation: 844

def palindrome_integer(number):
    return type(number) == int and str(number)[::-1] == str(number)

Don't hesitate to comment if you have problem in understanding the solution.

Upvotes: 0

Abhijit Sarkar
Abhijit Sarkar

Reputation: 24593

One-liner:

return isinstance(n, int) and str(n) == str(n)[::-1]

Or slightly more contrived:

import re
x = str(n)
return re.match(r”\d+“, x) and x == x[::-1]

Upvotes: 1

Ralubrusto
Ralubrusto

Reputation: 1501

If you want to check if number is integer, you should use isistance.

def palindrome_integer(number): 

    if not isinstance(number, int):
        return False
    elif str(number) == str(number)[::-1]:
        return True
    else:
        return False

The rest of your code seems to work fine.

Upvotes: 2

Related Questions