18
votes

Using Python, reverse an integer and determine if it is a palindrome. Here is my definition of reverse and palindrome. Do I have a correct logic?

def reverse(num):
    s=len(num)
    newnum=[None]*length
    for i in num:
        s=s-1
        newnum[s]=i
        return newnum

def palindrome(num):
    a=str(num)
    l=len(z)/2
    if a[:1]==a[-1:][::-1]:
        b=True
    else:
        b=False

I am having some trouble to write def main.

13
What's wrong with the code you have? Does it not work? - Joel Cornett
I've done the def main part as well, but it says my input has no len. - YXH
Which part? Post the traceback for the error. - Joel Cornett
You're passing an integer to reverse(). Integers don't have a "length", only strings and sequences have lengths. - Joel Cornett

13 Answers

55
votes
def palindrome(num):
    return str(num) == str(num)[::-1]
18
votes

Integer numbers don't have len().

Testing if a number is a palindrome is as simple as testing if the number is equal to its reverse (though if you want maximum efficiency you can just compare characters from both ends of the string until you reach the middle).

To find the reverse of an integer you can either do it the hard way (using mod % and integer division // to find each digit and construct the reverse number):

def reverse(num):
  rev = 0
  while num > 0:
    rev = (10*rev) + num%10
    num //= 10
  return rev

Or the easy way (turning the number into a string, using slice notation to reverse the string and turning it back to an integer):

def reverse(num):
  return int(str(num)[::-1])
1
votes

This is an unreadable one-line recursive implementation based in part on the answer by pedrosorio.

def reverse(i):
    return int(i!=0) and ((i%10)*(10**int(math.log(i,10))) + reverse(i//10))

def is_palindrome(i):
    return i == reverse(i)

It works for integer i ≥ 0.

Note that reverse(123) == reverse(1230) == 321. This is not a problem, considering any nonzero integer that ends with 0 cannot be a palindrome anyway.

Note also that complete reversal of the integer may of course not be necessary to determine if it's a palindrome. The reversal may be implemented so as to be aborted early if the number is determined to not be a palindrome.

1
votes

Long but readable:

def palindrome(x):
    a=""
    x=str(x)
    for i in range(len(x),0,-1):
        a+=x[i-1]
        print a
    if a==x:
        return True
    else:
        return False
1
votes
def revers(num):
    rev = 0
    while num > 0:
        rem = num % 10
        rev = (rev * 10) + rem
        num = num // 10
    return rev  
0
votes

I used a list for this program, works with strings too.

print('Enter Something')
a = list(input())
for i in range ((len(a)),0,-1):
   print (a[i-1],end='')
0
votes
import math

a = raw_input("Enter number:")
n = -1

reverse = 0    
for i in a:
        n += 1
        digit = math.pow(10,n)
        reverse = int(i)*digit + reverse

print int(reverse)  

if int(reverse) == int(a):
        print "Palindrome"
else:
        print ":("
0
votes

This code converts int to String and then checks if the string is pallindrome. The advantage is that it is fast, the disadvantage being that it converts int to String thereby compromising with the perfect solution to question.

It handles negative int as well.

class Solution:
    def isPalindrome(self, x):
        """
        :type x: int
        :rtype: bool
        """
        s = str(x)
        if x >=0 :
            if s == s[::-1]:
                return True
            else:
                return False
        else:
            return False
0
votes
t=int(input("enter nos of test cases= "))
while t>0:
    n=int(input("enter number="))
    rev=0
    while n>0:
        digit=n%10
        rev=rev*10+digit
        n=n//10
    print(rev)
    t-=1
0
votes

Here is my solution.

z=input('input number')
if int(z) == int(str(z)[::-1]):
    print('The number is palindrome')
else:
    print('The number is not palindrome')
0
votes

Reverse an integer and determine if it is a palindrome:

  1. Convert integer to string.
  2. Use reverse function to reverse the string and join it.
  3. Check if reversed number = original number with if else condition.

See code:

number = 1221

reverse = ''.join(reversed(str(number)))

print(reverse)

if (int(reverse) == number):
    print("number is Palindrome")
else:
    print("number is not Palindrome")
-2
votes

I try to come out with this myself.

def number():

    n = int(input("Enter a number: "))
    return n

def reverse(n):


    total = ""
    while n > 0:
        a = n % 10

        n//= 10


        total+= str(a)

    return total


def palindrome (n):

    total = 0
    while n > 0:
        a = n % 10

        n//= 10


        total+= a

    if total == n:
        x = "This number has a palindrome"

    else:
        x = ""

    return x

n = number()
print (reverse(n))
print (palindrome(n))
-2
votes
original = raw_input("Enter a no = ")   #original = number entered by user
rev = original[::-1]     #rev = reverse of original by useing scope resolution 
print 'rev of original no =',rev
if original == rev:
    print "no's are equal"
else:
    print "no's are not equal"