A palindrome is a word, phrase, number, or another sequence of units that can be read the same way in either direction, with general allowances for adjustments to punctuation and word dividers. When its digits are reversed, they turn out to be the same number as the original number. Palindromes can be numeric as well. For example, madam, 1234321. This blog will teach us how to create a Palindrome in Python.
If you want to dive further, check out this free course on Palindrome in Python and PG Programs on Software Engineering. It covers the fundamentals of python programming, such as its syntax, variables, data types, operators, tokens, and strings. This course also offers you a certificate on completion to help you stay ahead of the competition.
- 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?
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 is a collection of numbers that remains the same when read backward. These numbers are also said to be symmetrical. When its digits are reversed, they turn out to be the same number as the original number. E.g., 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 is different from the original.
What is a Palindrome String?
A Palindrome String is a collection of alphabets that remains the same when read backward. They are also called Symmetrical Alphabets. When its alphabets are written in reverse order, they turn out to be the same combination of alphabets as the original string. E.g., “madam” is a Palindrome. If 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 the Palindrome Phrase?
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Phrase is a collection of words and special characters that remains the same way when read backward. These phrases are also said to be symmetrical. When the phrase is reversed, it turns out to be the exact same phrase as the original one. For eg : a1b2c33c2b1a is a Palindrome. If the phrase is reversed, it again becomes a1b2c33c2b1a, our original phrase. a4b523kg is not a Palindrome. When reversed, the new number becomes gk325b4a which is different from the original phrase.
Palindrome Examples
Below are a few examples of Palindromes:
- Mom
- Madam
- a2332a
- Rubber
- Dad
- 123454321
Trivia: Is 02/02/2020 a palindrome string when considered a palindrome phrase?
Palindrome in Python Algorithm
You can enroll in these Python-related courses to get comfortable in Python Programming Language and get your free certificate on Great Learning Academy before practicing Palindromes algorithm and code in Python.
Now how to create Palindromes in Python?
Consider the algorithm for the Problem Statement: Find if a string is a Palindrome or not.
- Check if the index first and index last letters are the same; if not the 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 let us consider an algorithm for the Problem Statement: Find if a number is a Palindrome or not.
- Copy the input number in another variable to compare them later.
- Next, we reverse the given number. To reverse the number, follow these steps:
- Isolate the last digit of a number. The modulo operator (%) returns the remainder of a division
- Append lastDigit to reverse. reverse = (reverse * 10) + lastDigit.
- Remove the last digit from the number. number = number / 10.
- Iterate this process. 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, else 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
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:
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:
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!