Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Find All Palindromes in a Python String?

#1
How to Find All Palindromes in a Python String?

5/5 – (1 vote)

Coding Challenge


? Challenge: Given a string. How to find all palindromes in the string?

For comprehensibility, allow me to quickly add a definition of the term palindrome:

? Definition: A palindrome is a sequence of characters that reads the same backward as forward such as 'madam', 'anna', or '101'.

This article wants to give you a quick and easy solution in Python. First, we’ll solve the easier but important problem of checking if a substring is a palindrome in the first place:

How to Check If String is Palindrome


You can easily check if a string is a palindrome by using the slicing expression word == word[::-1] that evaluates to True if the word is the same forward and backward, i.e., it is a palindrome.

? Recommended Tutorial: Python Palindromes One-Liner

Next, we’ll explore how to find all substrings in a Python string that are also palindromes. You can find our palindrome checker in the code solution (highlighted):

Find All Substrings That Are Palindrome


The brute-force approach to finding all palindromes in a string is to iterate over all substrings in a nested for loop. Then check each substring if it is a palindrome using word == word[::-1]. Keep track of the found palindromes using the list.append() method. Return the final list after traversing all substrings.

Here’s the full solution:

def find_palindromes(s): palindromes = [] n = len(s) for i in range(n): for j in range(i+1,n+1): word = s[i:j] if word == word[::-1]: palindromes.append(word) return palindromes print(find_palindromes('locoannamadam'))
# ['l', 'o', 'oco', 'c', 'o', 'a', 'anna',
# 'n', 'nn', 'n', 'a', 'ama', 'm', 'madam',
# 'a', 'ada', 'd', 'a', 'm'] print(find_palindromes('anna'))
# ['a', 'anna', 'n', 'nn', 'n', 'a'] print(find_palindromes('abc'))
# ['a', 'b', 'c']

Runtime Complexity


This has cubic runtime complexity, i.e., for a string with length n, we need to check O(n*n) different words. Each word may have up to n characters, thus the palindrome check itself is O(n). Together, this yields runtime complexity of O(n*n*n) = O(n³).

Quadratic Runtime Solutions


Is this the best we can do? No! There’s also an O(n²) time solution!

Here’s a quadratic-runtime solution to find all palindromes in a given string that ignores the trivial one-character palindromes (significantly modified from source):

def find_palindromes(s, j, k): ''' Finds palindromes in substring between indices j and k''' palindromes = [] while j >= 0 and k < len(s): if s[j] != s[k]: break palindromes.append(s[j: k + 1]) j -= 1 k += 1 return palindromes def find_all(s): '''Finds all palindromes (non-trivial) in string s''' palindromes = [] for i in range(0, len(s)): palindromes.extend(find_palindromes(s, i-1, i+1)) palindromes.extend(find_palindromes(s, i, i+1)) return palindromes print(find_all('locoannamadam'))
# ['oco', 'nn', 'anna', 'ama', 'ada', 'madam'] print(find_all('anna'))
# ['nn', 'anna'] print(find_all('abc'))
# []

Feel free to join our community of ambitious learners like you (we have cheat sheets too): ❤



https://www.sickgaming.net/blog/2022/09/...on-string/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Int to String with Trailing Zeros xSicKxBot 0 36 12-01-2025, 05:47 PM
Last Post: xSicKxBot
  [Tut] Wrap and Truncate a String with Textwrap in Python xSicKxBot 0 2,054 09-01-2023, 07:45 PM
Last Post: xSicKxBot
  [Tut] Write a Long String on Multiple Lines in Python xSicKxBot 0 1,503 08-17-2023, 11:05 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,555 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,695 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] F-String Python Hex, Oct, and Bin: Efficient Number Conversions xSicKxBot 0 1,669 03-28-2023, 12:01 PM
Last Post: xSicKxBot
  [Tut] How to Correctly Write a Raw Multiline String in Python: Essential Tips xSicKxBot 0 1,492 03-27-2023, 05:54 PM
Last Post: xSicKxBot
  [Tut] How To Extract Numbers From A String In Python? xSicKxBot 0 1,317 02-26-2023, 02:45 PM
Last Post: xSicKxBot
  [Tut] Python | Split String and Remove newline xSicKxBot 0 1,292 12-16-2022, 10:38 PM
Last Post: xSicKxBot
  [Tut] Python | Split String with Regex xSicKxBot 0 1,414 12-13-2022, 06:04 AM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016