- 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
What is Palindrome?
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 reading them backwards 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 and go step by step and come up with various solutions to check if the string is a palindrome or not.
Palindrome is defined as a word, phrase, number,or other sequence of characters which 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 is a collection of numbers which remains the exact same way when read backwards. These numbers are also said to be symmetrical. When its digits are reversed, they turn out to be the exact same number as the original number. For eg : 1234321 is a Palindrome. It its digits are reversed, it again becomes 1234321 which was our original number. 1234232 is not a Palindrome. When reversed, the new number becomes 2324321 which is not the same as the original number.
What is a Palindrome String?
A Palindrome String is a collection of alphabets which remains the exact same way when read backwards. They are also called Symmetrical Alphabets. When its alphabets are written in reverse order, they turn out to be the exact same combination of alphabets as the original string. For eg : “madam” is a Palindrome. It its alphabets are reversed, it again becomes “madam” which was our original string. “napkin” is not a Palindrome. When reversed, the new number becomes “nikpan” which is different from the original string.
What is a Palindrome Phrase?
Palindrome Phrase is a collection of words and special characters, which remains the exact same way when read backwards. These phrases are also said to be symmetrical. When the phrase is reversed, they turn out to be the exact same phrase as the original phrase. For eg : a1b2c33c2b1a is a Palindrome. It the phrase is reversed, it again becomes a1b2c33c2b1a which was our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Below are a few examples of Palindromes
Trivia: Is 02/02/2020 a palindrome string when considered as a palindrome phrase?
We will look at the logical steps of building a solution for checking strings that have the palindrome property.
Palindrome in Python Algorithm
Consider the algorithm for the Problem Statement: Find if a string is Palindrome or not
- Check if the index first and index last letters are the same; if not same return false
- Repeat step 2 by incrementing the first index and decrementing the last index
- Repeat step 3 while first < last If( first > last) then return True
Now that we have the algorithm let us convert it into code by following the similar logic.
Palindrome in Python Code
Using While Loop
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 also enables us to use the reverse function. We know intuitively that a word read forwards and backwards, if same is a palindrome. Hence, let us generate the forward and backward string 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 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. Linked list is a data structure that has 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() print(,end='->') print( list_4.palindrome())
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 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.
Therefore, we define a function called palindrome, which has parameters node, var( stands for variable), previous and temp. We jump till the end of the list using the variable var in line 29, and meanwhile we store the previous 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() Print( list_4.palindrome())
In this article, we looked at palindromes inside out and understood them thoroughly. Try coming up with 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.
Check out our Python Guide to learn Python yourself
Learn how to find the Factorial of a Number in Python
Learn to print the Fibonacci series in Python0