Reversing String in Python

Reversing String in Python

Introduction

A Palindrome is a word, number, phrase, or set of characters that read the same backward as they do forwards. When its digits are reversed, they turn out to be the same number as the original number.
For example MADAM, 1234321.

Being focused on digits (integer), here we will be analyzing some of the methods to check if a number is palindrome or not by reversing the provided number. There are plenty of ways to perform palindrome check using Python.

Reversing Number

Firstly, let’s discuss some of the approaches to reverse a number.

Algorithm for Reversing Integer

Let’s begin with the algorithm that makes it easy to understand the program.Ask for input from the user and store it to the original_number variable.

  1. Initialize variable reversed_number = 0

  2. Loop while original_number > 0.

    Multiply reversed_number by 10 and add remainder of original_number divided by 10 to reversed_number

reversed_number = reversed_number * 10 + original_number % 10

Divide num by 10

  1. Return reversed_number

Mathematical Approach

Now, let's implement the above algorithm in Python, where the value of an integer is stored in a variable that is checked using a condition, and each digit of the number is stored in another variable that prints the reversed number. Numbers can be reversed in Python using different methods. Let’s analyze some of them using Python.

# Takes input from user and store on original_number
original_number = int(input('Enter an integer: '))
# Initialize reveresed_number to 0
reversed_number = 0

# Loop while original_number is greater than 0
while original_number > 0:
    # Get remainder of original_number divided by 10
    remainder = original_number % 10
    # Multiply reveresed_number by 10 and add remainder
    reversed_number = reversed_number * 10 + remainder
    # Perform integer division to original_number and store in itself.
    original_number = original_number // 10

# Print the reversed number
print('Reversed Number: ', reversed_number)

The output for the above program is:

Enter an integer: 45641
Reversed Number: 14654

That’s the one way to get the reversed integer with the mathematical approach. Also, there are other approaches to meet our objectives.

String Reversal Approach

We can convert a number to a string, reverse the string, and display the reversed number. The code for this approach is written below:

# Take input from user
original_number = int(input('Enter an integer : '))
# Convert the number into string
str_number  = str(original_number)
# Reverse string
reversed_str_number = str_number[::-1]
# Print the reversed string as number
print('Reversed Number', int(reversed_str_number))

The [::-1] operation is one-liner for reversing an iterable i.e. lists, strings, tuples etc. which can be iterated.

The output for the above program is:

Enter an integer : 4654
Reversed Number 4564

List Reversal Approach

We can reverse the number using the List Reversal method. With this approach, we first take an input as integer and convert it into strings. Then the string is converted to list. Then list is then reversed. The reversed list is joined to form a string and we return the integer representation of thaat generated string. The code for this approach is written below:

# Take input from user
original_number = int(input('Enter an integer : '))
# Converting number into list
lst_number = list(str(original_number))
# applying reverse method of list
lst_number.reverse()
# Converting list into number
reversed_number = ''.join(lst_number)
# Print the reveresed string as number
print ("Reverse of the provided number is : ", int(reversed_number))

The output for the above program is:

Enter an integer : 5464
Reverse of the provided number is :  4645

Now that we've looked at some methods for reversing a number, let's look at some methods for determining whether or not a number is a palindrome.

Palindrome Number

Firstly, let’s know about the palindrome number at first. A palindromic number (also known as a numeral palindrome or a numeric palindrome) is a number that remains the same when its digits are reversed.

For eg: Let’s take a number : 14641 which is same when reversed i.e 14641. There are many other palindrome numbers starting from 11, 22, 33, 44, 55, 66, 77, 88, 99, 101 to infinity.

Let's look at an algorithm for determining whether or not a number is a palindrome.

Algorithm for Palindrome Check

Ask for input from the user and store it to the original_number variable. Also copy it in copy_number variable
(1) Initialize variable reversed_number = 0
(2) Loop while original_number > 0
        (a) Multiply reversed_number by 10 and add remainder of original_number divided by 10 to reversed_number
                reversed_number = reversed_number * 10 + original_number % 10  
        (b) Divide original_number by 10  
(3) Check if copy_number is equal to reversed_number.
(4) If equal, the provided number is palindrome number, else not a palindrome number.

Let’s implement this with a Python program.

Palindrome Check using Mathematical Approach

# Takes input from user and store on original_number
original_number = int(input('Enter an integer: '))
# Store a copy of the original_number because the 
# state of original_number changes in each iteration.
copy_number = original_number
# Initialize reveresed_number to 0
reversed_number = 0

# Loop while original_number is greater than 0
while original_number > 0:
    # Get remainder of original_number divided by 10
    remainder = original_number % 10
    # Multiply reveresed_number by 10 and add remainder
    reversed_number = reversed_number * 10 + remainder
    # Perform integer division to original_number and store in itself.
    original_number = original_number // 10

# Compare if copY_number  is equal to reversed_number
if copy_number == reversed_number:
    print(copy_number, 'is a palindrome number')
else:
    print(copy_number, 'is not a palindrome number')

The output for this program is:

Enter an integer: 12321
12321 is a palindrome number

This was a success scenario i.e. the provided number was a palindrome number. Let's run this program with a non-palindrome number, 4545, and see what happens.

Enter an integer: 4545
4545 is not a palindrome number

That is correct, and this program thoroughly checked a number's palindrome property.

However, the program we wrote was lengthy, so let's look at other methods for determining whether or not a number is a palindrome.

Palindrome Check using String Reversal

number = int(input('Enter a number : '))

if number == int(str(number)[::-1]):
    print(number, 'is palindrome.')
else:
    print(number, 'is not palindrome.')

The output for this program is :

Enter a number : 454
454 is palindrome.

Enter a number : 456
456 is not palindrome.

In this program, we took a integer number as input and stored in a number variable. Then number is then converted to string and got reversed. Then reversed number is then compared to integer and compared with the number variable. Thus, we found if number is palindrome or not.

Palindrome Check using Function

We can even create a function to check the palindrome property of a number.

# Function for checking if a number is palindrome or not.

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

number = int(input('Enter an integer: '))
print(number, 'is a palindrome number ?', isPalindrome(number))

The output for this program is:

Enter an integer: 456
456 is a palindrome number ? False

Enter an integer: 78987
78987 is a palindrome number ? True

Creating a function we can reuse this frequently as per out need and it makes our code cleaner.

Palindrome Check using Class Inheritance

We can append this function to the int class that Python provides the functionality to check if the provided number is palindrome or not with inheritance of int class.

# `Number` Class inheriting the `int` class

class Number(int):
    def __init__(self, num: int):
        self.num = int(num)

    def isPalindrome(self):
        if self.num == int(str(self.num)[::-1]):
            return True
        else:
            return False

    def __str__(self):
        return str(self.num)


number = Number(input('Enter an integer: '))
print(number, 'is a palindrome number ?', number.isPalindrome(number))

The benifit of this approach is that we can even use other properties and methods of int class as Number class inherits it.

Time Complexity

Though, this class based approach looks like overkilling for checking just if a number is palindrome number or not, it doesn’t take much time to calculate.

import time
start_time = time.time()
number = Number(456)
number.isPalindrome()
end_time = time.time()
total_time = end_time - start_time
print("Time: ", total_time, 'ms')

Output

Time:  1.3589859008789062e-05 ms

In this way, we can compare and check if a number is a palindrome number or not by reversing the provided number in Python.