Palindrome in Python | Python for Data Science | Day 6
The Data Monk community is back with another new topic for you. It’s time for some programming, as we discuss the palindrome program in python. But, before you open your notebooks, let’s discuss what really is a palindrome.
Palindrome is a string that spells the same when read backwards. To give it a try, look at the image above. Let’s intuitively discuss how we can figure out if a string is a palindrome or not.
The most naive approach is to check if a string is a palindrome or not:
STEP 1: Reverse the string.
STEP 2: Check if reverse is equal to the original string.
STEP 3: If reverse = original string, it’s a palindrome. Else, not.
Now, let’s implement the code for this approach:
Another approach to figure out if a string is palindrome or not is to iteratively store each character of the string in a new variable and then check if the original string is equal to the reversed string.
Check the code below to implement the approach:
Let’s discuss another approach. In this one, we use two status pointers. The first pointer is placed on the left-most index and the second is placed on the right-most index. If we start matching the variables on these pointers and then update the status of the flag variable accordingly, we can find out if the given string is palindrome or not. The code for this approach is given below:
A homework for you: Visit http://componentsprogramming.com/palindromes/ to analyze the time complexity of various palindrome programs and find out the best approach.
Make sure you revise the codes given above and attempt the following question:
The questions have been answered for your convenience. But you know the drill, try these on your own first.
We have covered 40+ complete Data Science company interviews from the candidates who cracked these interviews.
Data Science Companies interview questions
We also have 30+ e-books on Amazon, Insta Mojo and books which can be delivered directly on your email address
Complete Set of e-books from The Data Monk
Understand some of the very complex topics in Analytics which are asked in most of the interviews
The Data Monk Top Articles
How to become a Data Scientist? Complete study material, free resources and websites to practice
Become a Data Scientist
Make your profile on our website and practice at least 5-7 questions per day. Be a part of ~2000 Analytics expert
Intern | The Data Monk