Palindrome Numbers in Python

Palindrome numbers are fascinating mathematical properties used in various domains, including mathematics, computer science, and cryptography. When the digits of a number are reversed, the number nevertheless remains the same. For instance, the numbers 121, 242, and 12321 are all palindromes. In this article, we'll talk about palindrome numbers in Python and how to code them. We'll also look at some intriguing mathematical characteristics of palindrome numbers and how they're used in computer science.

What is Palindrome?

A word, phrase, number, or string of characters that stays the same when its letters or digits are reversed is known as a palindrome. A palindrome is a word that reads the same forward and backwards, as the term "racecar." Similarly, the number "121" is a palindrome since it is the same number when its digits are reversed. You can refer to this article to know more about palindromes.

You can write a program to check if a number is a palindrome or not in Python. 

Methods to check if a number is a palindrome
 

1. Using simple iteration

These steps can be used in Python to determine whether a number is a palindrome or not using basic iteration:

  • Utilize the str() function to transform the number into a string.
  • Create two variables, ‘start’ and ‘end’, and set them to, respectively, point to the string's first and last character.
  • Use a loop to repeatedly iterate over the string until the start and end meet.
  • Use indexing and an if statement to compare the characters at the start and finish points within the loop.
  • Using the break statement, you can leave the loop if the letters are different and the number is not a palindrome.
  • If there is no break statement after the loop has finished, the number is a palindrome.

Python code to check if a number is a palindrome using iteration:

def is_palindrome(num):
    str_num = str(num)
    start = 0
    end = len(str_num) - 1
    while start < end:
        if str_num[start] != str_num[end]:
            return False
        start += 1
        end -= 1
    return True

print(is_palindrome(121))  # True
print(is_palindrome(12321))  # True
print(is_palindrome(12345))  # False

Another way to check whether a number is a palindrome or not in Python is by using string slicing. This approach requires string slicing to reverse the string after converting the number to a string. The number is a palindrome if the reversed string matches the original string exactly. The Python code to determine whether a number is a palindrome using string slicing is as follows:

def is_palindrome(num):
    str_num = str(num)
    rev_str = str_num[::-1]
    if str_num == rev_str:
        return True
    else:
        return False

print(is_palindrome(121))  # True
print(is_palindrome(12321))  # True
print(is_palindrome(12345))  # False

The is_palindrome() method in the above code turns an integer into a string using the str() method. The string is then reversed and stored in rev_str using string slicing with a step of -1. The code then uses the if statement to compare the original string str_num with the reversed string rev_str. The function returns True, indicating that the number is a palindrome if the two strings are identical. The function returns False, indicating that the number is not a palindrome if the strings are not identical.

2. Using recursion

In Python, recursion can be used to determine whether a given integer is a palindrome or not. When using recursion, a problem is divided into smaller subproblems and then solved recursively. The following Python code uses recursion to determine whether an integer is a palindrome:

def is_palindrome(num):
    str_num = str(num)
    if len(str_num) <= 1:
        return True
    else:
        if str_num[0] != str_num[-1]:
            return False
        else:
            return is_palindrome(str_num[1:-1])

print(is_palindrome(121))  # True
print(is_palindrome(12321))  # True
print(is_palindrome(12345))  # False


The is_palindrome() method in the above code turns an integer into a string using the str(). The function returns True, indicating that the number is a palindrome if the length of the string is one or less.

The method uses an if statement to compare the string's initial and last characters if its length is more than 1. The function returns False if the characters are different, indicating that the number is not a palindrome. If the first and last characters match, the function calls itself recursively using the string that results from string-slicing the first and last characters.

3. Using built-in reverse function

The join() and reversed() methods in Python can be used to reverse the digits of a number as a string and determine if it is a palindrome. The following Python code uses reverse = "” .join(reversed(str)) to determine whether a number is a palindrome-

def is_palindrome(num):
    str_num = str(num)
    reverse_str = "".join(reversed(str_num))
    if str_num == reverse_str:
        return True
    else:
        return False
print(is_palindrome(121))  # True
print(is_palindrome(12321))  # True
print(is_palindrome(12345))  # False

The is_palindrome() method in this code turns an integer into a string using the str() function. The string is then reversed using the reversed() method, and the characters are joined together into a new string using the join() function.

The code then uses the if statement to compare the original string str_num with the inverted string reverse_str. The function returns True, indicating that the number is a palindrome if the two strings are identical. The function returns False, indicating that the number is not a palindrome if the strings are not identical.

The approach we covered before that used string slicing is identical to this one, but it uses the join() and reversed() functions instead. You can choose whichever way is more readable and practical because they both yield the same result and are equally valid.

Conclusion

We have now looked at a variety of techniques to determine whether a number is a palindrome in Python. We began with using a straightforward iteration technique that checks a number's palindrome status using loops and conditional expressions. After that, we examined three other techniques, including text slicing, recursion, and the use of built-in functions like reverse() and join().

Each approach has pros and cons in terms of readability, effectiveness, and complexity. Which approach to adopt relies on the particular requirements. Using a straightforward iterative method may be the most suitable course of action if you need to optimise speed while working with enormous quantities. On the other hand, using built-in methods like reversed() and join() or recursive functions may be more appropriate if you're more concerned with readability and simplicity.


Similar Articles