Computer >> Computer tutorials >  >> Programming >> Python

Check if all the palindromic sub-strings are of odd lengths in Python


Suppose we have a string s we have to check whether its palindromic sub-strings are of odd length or not.

So, if the input is like s = "levelopmadam", then the output will be True as there are two palindromic substrings "level" and "madam" both are of odd length.

To solve this, we will follow these steps −

  • for i in range 0 to size of s, do
    • temp := blank string
    • for j in range i to size of s, do
      • temp := temp concatenate s[j]
      • if size of temp is even and temp is palindrome, then
        • return False
  • return True

Let us see the following implementation to get better understanding −

Example

def is_palindrome(s):
   return s == s[::-1]
def solve(s):
   for i in range(len(s)):
      temp = ""
   for j in range(i, len(s)):
      temp += s[j]
      if len(temp) % 2 == 0 and is_palindrome(temp):
         return False
   return True
s = "levelopmadam"
print(solve(s))

Input

"levelopmadam"

Output

True