
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find All Palindromic Substrings of a Given String in Python
Suppose we have a string; we have to find all the palindromic sub-strings from that string. Here aa and aa are considered as two sub-strings, not one.
So, if the input is like redivider, then the output will be ['r', 'e', 'd', 'i', 'v', 'ivi', 'divid', 'edivide', 'redivider', 'i', 'd', 'e', 'r']
To solve this, we will follow these steps −
- v := a new list
- pos := 0.0
- while pos < size of s, do
- rad := pos - (pos as integer)
- while (pos + rad) < size of s and (pos - rad) >= 0 and (s[integer of (pos - rad)] is same as s[integer of (pos + rad)]), do
- insert s[from index integer of (pos - rad) to integer of (pos + rad + 1)] at the end of v
- rad := rad + 1
- pos := pos + 0.5
- return v
Example Code
Let us see the following implementation to get better understanding −
def get_all_pal_sub(s): v = [] pos = 0.0 while pos < len(s): rad = pos - int(pos) while ((pos + rad) < len(s) and (pos - rad) >= 0 and (s[int(pos - rad)] == s[int(pos + rad)])): v.append(s[int(pos - rad): int(pos + rad + 1)]) rad += 1 pos += 0.5 return v v = get_all_pal_sub("redivider") print(len(v)) print(v)
Input
"redivider"
Output
13 ['r', 'e', 'd', 'i', 'v', 'ivi', 'divid', 'edivide', 'redivider', 'i', 'd', 'e', 'r']
Advertisements