Palindrome Program in Python
Our fascination with long stretches of odd numbers or sequences persisted as we grew older and gained more computing knowledge. When we were younger, reading reverse strings was entertaining. Later, as we developed into computer science fans, we discovered that strings in Python that read the same both ways are known as palindromes. Explore why you should learn Python. Discover how to use the while loop and built-in methods in Python to find a palindrome number if you’re a fan of the language and enjoy coding.
What is Palindrome?
Python requires that a number or string be the same when it is reversed to be considered a palindrome. It is not a palindrome if the string or number changes when it is turned back on its head. Check also how multithreading in Python is accomplished.
Example: 121, 3113, 12521, and 585585 are palindrome numbers in Python.
DID, DEED, and ROTATOR are palindrome strings in Python.
Consequently, any word, number, sentence, or string that appears the same both forward and backward in Python is called a palindrome.
Palindrome Algorithm
- Analyze the letter or number.
- Keep the digit or letter as a short-term variable.
- Turn the letter or number backward.
- Comparing the temporary variable to a letter or integer that has been reversed.
- Print “This string/number is a palindrome” if the two characters or digits are the same.
- In the alternative, display “This string/number is not a palindrome.”
Methods to Check Palindrome in Python
It is possible to determine whether a given string or integer is a palindrome using a Python palindrome program. Furthermore, there are numerous ways in Python to ascertain this; as novices or students of Python, we have encountered this on multiple occasions.
Method 1: Using the built-in method
Method 2: Using reverse and compare method
Method 3: Using reverse and join method
Method 4: Using the Recursion Method
Method 5: Using for loop
Method 6: Using a while loop
Method 7: Using an iterative loop
Recommended read: Goto statement in Python | Jump statements in Python
Using the ‘built-in’ method
This method reverses the string using the predefined function “‘.join(reversed(string)).”.
def isPalindrome(s):
rev = ”.join(reversed(s))
if (s == rev):
return True
return False
s = “madam”
ans = isPalindrome(s)
if (ans):
print(“Yes”)
else:
print(“No”)
Output
Enter string: madam
The string is palindrome
Here, we can use Python’s built-in ‘reversed(sequence)’ function to verify the value for palindromes by converting the input number to a sequence and applying the reversed method to identify the reverse of the sequence. Then, by contrasting these two sequences, the palindrome can be confirmed. Learn about method overloading in Python and get expertise in coding.
Using the reverse and compare method
To apply the previously discussed approach, we will first locate the reversed string and then compare it with the original string. If the strings match up, it’s a palindrome.
Example
def isPalindrome(string):
if (string == string[::-1]) :
return ”The string is a palindrome.”
else:
return ”The string is not a palindrome.”
string = input (“Enter a string to check: ”)
print(isPalindrome(string))
Output
Enter a string to check: noon
The string is a palindrome.
Get a complete understanding of programming skills and check your proficiency using our Python interview questions and answers.
Using the ‘reverse’ and ‘join’ method
Here, we’ll use the built-in reversed() method to move over the characters in the string in reverse order. Next, we will compare the input string with the reversed string to see if it is a palindrome. This is comparable to the compare and reverse approach.
def isPalindrome(string):
revstr=”.join(reversed(string))
if string==revstr:
return ”The string is a palindrome.”
return ”The string is not a palindrome.”
string = input (“Enter string: ”)
print(isPalindrome(string))
Enter string: malayalam
The string is a palindrome
The code above declares the isPalindrome() function and passes in a string as an argument. Next, the function body receives the input string and uses the reversed() method to loop backward through the string’s characters. The reversed characters are then combined using the join() method and stored in the revstr variable. Explore a wide range of Python libraries for data analysis and gain expertise in them.
Using the ‘recursion’ method
The recursion method, which this method employs, involves the function calling itself to reverse a string. Then, just like in the other instances, we check to see if the original string and the reversed string match.
def isPalindrome(string):
if len(string) < 1:
return True
else:
if string[0] == string[-1]:
return isPalindrome(string[1:-1])
else:
return False
str1 = input(“Enter string : ”)
if(isPalindrome(str1)==True):
print(“The string is a palindrome.”)
else:
print(“The string is not a palindrome.”)
Output
Enter string: vivid
The string is not a palindrome
In the code above, the isPalindrome() method has been declared again and is sent a string parameter. Alternatively, if the string’s end character equals its beginning character, the method is called recursively with the parameter representing a slice string with the first and last characters eliminated, returning false otherwise. We use an if statement to determine if the received answer is True or False before printing the result as needed. Learn about building web applications with Django.
Using ‘For Loop’
This method uses a for loop to iterate through each character in the supplied string, merging each element stored in an empty variable we define.
string = input(“Enter string : ”)
revstr = ””
for i in string:
revstr = i + revstr
print(“Reversed string : ”, revstr)
if(string == revstr):
print(“The string is a palindrome.”)
else:
print(“The string is not a palindrome.”)
Output
Enter string: kayak
The string is a palindrome
As a result, if a string is the same in reverse, it is called a palindrome. Explore the various ways of working with data in Python: cleaning, wrangling, and preprocessing.
Using ‘While Loop’
A while loop is usually used instead of a for loop because it allows the program to use less memory for longer strings. It is the most popular option among programmers because the string does not need to be reallocated throughout loop execution.
def isPalindrome(string):
string = string.lower().replace(‘ ’, ”)
first, last = 0, len(string) - 1
while(first < last):
if(string[first] == string[last]):
first += 1
last -= 1
else:
return ”The string is not a palindrome.”
return ”The string is a palindrome.”
str1 = input(“Enter string : ”)
print(isPalindrome(str1)) #Returns True
Output
Enter string: redivider
The string is palindrome
Thus, in the code above, we declare the isPalindrome() function and pass in the text parameter first. Get started with object-oriented programming in Python.
Using an iterative loop
By checking the string’s first character from the last one, its second from the second last, and so on, we shall loop through length/2 in this approach. The string would not be a palindrome if there was a character mismatch.
def isPalindrome(string):
for i in range(int(len(string)/2)):
if string[i] != string[len(string)-i-1]:
return ”The string is not a palindrome.”
return ”The string is a palindrome.”
string = input (“Enter string: ”)
print(isPalindrome(string)
Output
Enter string: mom
The string is palindrome
In the code above, the isPalindrome() function has been declared and given a string argument. The function body then runs a for loop from range 0 to the input string’s center. While the for loop is running, we check to see if the nth index values from the front and the nth index values from the back match. Therefore, if they do not match, the string is not a palindrome. The string is a reversed pair if it isn’t. Do you want to know the difference between Java full-stack and Python full-stack? Explore here.
Conclusion
We believe you have a thorough grasp of how to implement a Palindrome in Python after reading this article. We encourage you to consider enrolling in SLA Institute’s Python training in Chennai if you want to improve your software development skills even further.