- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if suffix and prefix of a string are palindromes in Python
Suppose we have a string s, we have to check whether the string palindromes as its prefix and suffix substrings or not.
So, if the input is like s = "levelishighforracecar", then the output will be True as there are palindrome prefix and suffix: "level" and "racecar" respectively.
To solve this, we will follow these steps −
- l := size of s
- for i in range 2 to l + 2, do
- if substring of s up to index i is palindrome, then
- come out from loop
- if i is same as(l + 1) , then
- return False
- for i in range 2 to l + 2, do
- if substring of s from index (l - i) to (l - 1) is palindrome, then
- return True
- if substring of s from index (l - i) to (l - 1) is palindrome, then
- return False
- if substring of s up to index i is palindrome, then
Let us see the following implementation to get better understanding −
Example Code
def is_palindrome(s): return s == s[::-1] def solve(s): l = len(s) for i in range(2, l + 1): if is_palindrome(s[0:i]): break if i == (l + 1): return False for i in range(2, l + 1): if is_palindrome(s[l - i : l]): return True return False s = "levelishighforracecar" print(solve(s))
Input
"levelishighforracecar"
Output
True
Advertisements