A palindrome in Python is any sequence of elements like a word, phrase, or even a number that can be read the same way from both directions. When you reverse its characters, they are in the same sequence as the original word. For example, if you read madam from either left or right, it will be madam only. Palindromes can be numeric as well.
These patterns, known as palindromes, are not just interesting, but also practical to solve using programming. Whether you read them from the first character or from the end, they remain unchanged. In this blog, we’ll explore the thought process, step by step, and come up with various solutions to determine if a given input is a palindrome.
- What is Palindrome
- What is a Palindrome Number
- What is a Palindrome String
- What is a Palindrome Phrase
- Palindrome Examples
- Palindrome in Python Algorithm
- Palindrome in Python Code
a. using while loop
b. Using reverse function - Check if a Linked List is a Palindrome
Palindromes are of broadly 3 types, namely palindrome numbers, palindrome strings, palindrome phrases, collections of words, and special characters.
What is Palindrome?
A palindrome is a word, phrase, number, or another sequence of units that may be read the same way in either direction, generally if used comma-separated.
Happy belated multi-cultural palindrome day! 02/02/2020 was a unique day in February. It works whether your preferred date format is MM/DD/YYYY or DD/MM/YYYY or YYYY/MM/DD.
These patterns are called palindromes. Reading them from the first character or backward doesn’t make any difference. This is an interesting introductory problem to solve with the use of programming. In this blog, we will understand the thought process, go step by step, and come up with various solutions to check whether the string is a palindrome.
A palindrome is a word, phrase, number, or another sequence of characters that reads the same backward as forward.
They are classified into 3 types, which are Palindrome numbers,
Palindrome strings, Palindrome phrase: A collection of words and special characters.
What is a Palindrome Number?
A palindrome number in Python is a collection of numbers that remain the same when read from either direction. These numbers are also said to be symmetrical. When the digits are reversed, they are the same as the original.
For example, 1234321 is a Palindrome. If its digits are reversed, it again becomes 1234321, our original number. 1234232 is not a Palindrome. When reversed, the new number becomes 2324321, which differs from the original.
What is a Palindrome String?
A palindrome string is a collection of alphabets or letters that remains the same when read from either direction. If you write alphabets in reverse order, they are the same combination of alphabets as the original string.
E.g., “radar” is a Palindrome. If its alphabets are reversed, it again becomes “radar,” which was our original string. “napkin” is not a Palindrome. When reversed, the new string becomes “nikpan” which differs from the original string.
What is the Palindrome Phrase?
A palindrome phrase is a collection of words and special characters that remain the same when read from both ends. These phrases are also said to be symmetrical. When you reverse the phrase, it turns out to be the same as the original one.
For example, a1b2c33c2b1a is a Palindrome. If the words are reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new phrase becomes gk325b4a, which is different from the original phrase.
Palindrome Examples
Below are a few examples of Palindromes:
- Mom
- Madam
- a2332a
- Rubber
- Dad
- 123454321
Palindrome in Python Algorithm
Algorithm to Check for Palindrome in Python
The algorithm for the problem statement, Find if a string is a Palindrome or not, is as follows:
- Check if the digits on the first index are the same as the last index; if not the same, return false.
- Increment the first index and decrease the last index
- Repeat step 2 while first index < last index
- If( first index > last index), then return True
Now, let us consider an algorithm for the problem statement: Write the algorithm to find whether a number is a Palindrome number in python.
- Copy the input number in another variable to compare them later.
- Next, we logically reverse the given number. To do that, follow these steps:
- To isolate the last digit of a number, we need to find the modulo (%) of the number with 10, which returns the remainder, which is the last digit.
- Append lastDigit to reverse with the formula reverse = (reverse * 10) + lastDigit.
- Remove the last digit from the original number by performing number = number / 10.
- Repeat these steps while (number > 0)
- Now, we compare the reversed number with the original number.
- If the numbers are the same, then the number is a palindrome; otherwise, it is not.
Now that we have the algorithm, let us convert it into code by following a similar logic.
Palindrome in Python Code
Using While Loop (number)
number=int(input("Enter any number :"))
#store a copy of this number
temp=number
#calculate reverse of this number
reverse_num=0
while(number>0):
#extract last digit of this number
digit=number%10
#append this digit in reveresed number
reverse_num=reverse_num*10+digit
#floor divide the number leave out the last digit from number
number=number//10
#compare reverse to original number
if(temp==reverse_num):
print("The number is palindrome!")
else:
print("Not a palindrome!")
Using While-loop strings
def check_palindrome(string):
length = len(string)
first = 0
last = length -1
status = 1
while(first<last):
if(string[first]==string[last]):
first=first+1
last=last-1
else:
status = 0
break
return int(status)
string = input("Enter the string: ")
print("Method 1")
status= check_palindrome(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input – Madam
Output – It is a palindrome
This is a good approach, but Python enables us to use the reverse function. We know that a word read forwards and backward if the same is a palindrome. Hence, let us generate the forward and backward strings for the same and check if the two strings are the same.
Using Reverse Function
def check_palindrome_1(string):
reversed_string = string[::-1]
status=1
if(string!=reversed_string):
status=0
return status
string = input("Enter the string: ")
status= check_palindrome_1(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input: Enter the string: malayalam
Output: It is a palindrome
This is a good approach, but Python enables us to use the reverse function. We know that a word reads forwards and backward if the same is a palindrome. Hence, let us generate the forward and backward strings for the same and check if the two strings are the same.
Using Reverse Function
def check_palindrome_1(string):
reversed_string = string[::-1]
status=1
if(string!=reversed_string):
status=0
return status
string = input("Enter the string: ")
status= check_palindrome_1(string)
if(status):
print("It is a palindrome ")
else:
print("Sorry! Try again")
Input: Enter the string: malayalam
Output: It is a palindrome
Palindrome Program in Python
In this article, we will see different ways of implementing the palindrome program in Python
Palindrome String
Method 1:
- Finding the reverse of a string
- Checking if the reverse and original are the same or not
def isPalindrome(s):
return s == s[::-1]
# Driver code
s = "kayak"
ans = isPalindrome(s)
if ans:
print("Yes")
else:
print("No")
Steps:
- We create a function ispalindrome
- Return a variable by slicing the parameter in a reverse way
- In our driver code, we wrote a string
- Finally, in our if-else condition, we execute if it is a palindrome print yes or print no
Method 2:
- Using iterative loop
def isPalindrome(str):
for i in range(O, int(len(str)/2)):
if str[i] != str[len(str)-i-1]:
return False
return True
# main function
s = "kayak"
ans = isPalindrome(s)
if (ans):
print("Yes")
else:
print("No")
Steps:
- A loop is run from starting to half the length and checking the first character to the last character of the string.
- And check from the second character to the second last character of the string.
- If any of the characters are mismatched, it is not a palindrome.
Method 3:
- Using the in-built function to reverse a string
def isPalindrome(s):
rev = ‘'.join(reversed(s))
if (s == rev):
return True
return False
# main function
s = "kayak"
ans = isPalindrome(s)
if(ans):
print("Yes")
else:
print("No")
Steps:
In this method, we are using a predefined function ‘.join’
Method 4:
- Using recursion
def isPalindrome(s):
s = s.lower()
1 = len(s)
if 1 <2:
return True
elif s(0) == s{l - 1):
return isPalindrome(s[1: l - 1])
else:
return False
s = "Kayak"
ans = isPalindrome(s)
if ans:
print("Yes")
y else:
print("No")
Steps:
This method compares the first and last element of the string and gives the rest of the substring a recursive call to itself.
Palindrome in a Linked List
Let’s step this up and consider another data structure. What if the data is stored in a linked list? To tackle this, we need to understand linked lists. A linked list is a data structure with a non-contiguous allocation of memory.
We will begin by defining a linked list in python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def __init__(self,seq):
"""prepends item of lists into linked list"""
self.head = None
for item in seq:
node = ListNode(item)
node.next = self.head
self.head = node
def palindrome(self):
""" Check if linked list is palindrome and return True/False."""
node = self.head
var = node #var is initialized to head
prev = None #initially, prev is None
# prev approaches to middle of list till var reaches end or None
while var and var.next:
var = var.next.next
temp = node.next #reverse elements of first half of list
node.next = prev
prev = node
node = temp
if var: # in case of odd num elements
tail = node.next
else: # in case of even num elements
tail = node
while prev:
# compare reverse element and next half elements
if prev.val == tail.val:
tail = tail.next
prev = prev.next
else:
return False
return True
# Test Cases
list_1 = Solution([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7])
print([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7],end='->')
print(list_1.palindrome())
list_2 = Solution([6 , 3 , 4, 6])
print([6 , 3 , 4, 6],end='->')
print(list_2.palindrome())
list_3 = Solution([3, 7 ,3 ])
print([ 3 , 7, 3],end='->')
print(list_3.palindrome())
list_4 = Solution([1])
print([1],end='->')
print( list_4.palindrome())
Output –3, 7, 3 – True
1 – True
The logic for checking if a linked list is a palindrome or not is the modified version of the one we implemented on strings and arrays. We check if the reverse of the linked list is the same as the original sequence. Instead of reversing the entire linked list and storing it in a temporary location, we reverse the first half of the linked list and check if the first half and second half match after reversal.
Check out a* Algorithm in Artificial Intelligence.
Therefore, we define a function called palindrome, which has parameters node, var( stands for variable), previous, and temp. We jump to the end of the list using the variable var in line 29, and meanwhile, we store the last node data in variable prev. Therefore, comparing the prev.val and tail.val in line 41 gives us the answer.
# Test Cases
list_1 = Solution([7, 8, 6 , 3 , 7 ,3 , 6, 8, 7])
print(list_1.palindrome())
list_2 = Solution([6 , 3 , 4, 6])
print(list_2.palindrome())
list_3 = Solution([3, 7 ,3 ])
print(list_3.palindrome())
listl_4 = Solution([1])
Print( list_4.palindrome())
In this article, we looked at palindromes inside and out and understood them thoroughly. Try developing better implementation techniques using different data structures to improve your command over coding. We shall keep posting many more articles on implementing data structures and algorithms using Python Stay tuned and Read the Top Ten Python Books.
Further Reading
- Factorial of a Number in Python
- Convert list to string in Python
- Fibonacci series in Python
- Python Tutorial
- Eval function in Python
Kickstart your Python Journey with Great Learning, which offers free Python course with world-class training. Whether you’re interested in machine learning, data mining, or data analysis, Great Learning has a course for you!
Embarking on a journey towards a career in data science opens up a world of limitless possibilities. Whether you’re an aspiring data scientist or someone intrigued by the power of data, understanding the key factors that contribute to success in this field is crucial. The below path will guide you to become a proficient data scientist.