Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python, reverse an integer, and tell if palindrome

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.

like image 257
YXH Avatar asked Oct 24 '12 23:10

YXH


People also ask

How do you check if an integer is a palindrome in Python?

Example. num = input('Enter any number : ') try: val = int(num) if num == str(num)[::-1]: print('The given number is PALINDROME') else: print('The given number is NOT a palindrome') except ValueError: print("That's not a valid number, Try Again !")


2 Answers

def palindrome(num):
    return str(num) == str(num)[::-1]
like image 86
Peter Hull Avatar answered Oct 24 '22 21:10

Peter Hull


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])
like image 41
pedrosorio Avatar answered Oct 24 '22 21:10

pedrosorio