{"id":128100,"date":"2022-09-14T18:44:06","date_gmt":"2022-09-14T18:44:06","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=676729"},"modified":"2022-09-14T18:44:06","modified_gmt":"2022-09-14T18:44:06","slug":"how-to-find-all-palindromes-in-a-python-string","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2022\/09\/14\/how-to-find-all-palindromes-in-a-python-string\/","title":{"rendered":"How to Find All Palindromes in a Python String?"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload=\"{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;676729&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\\\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\\\/{best} - ({count} {votes})&quot;,&quot;font_factor&quot;:&quot;1.25&quot;}\">\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/div>\n<h2>Coding Challenge<\/h2>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4ac.png\" alt=\"\ud83d\udcac\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Challenge<\/strong>: Given a string. How to find all <a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/palindromes-in-one-line-python\/\" data-type=\"post\" data-id=\"3613\" target=\"_blank\">palindromes<\/a> in the string?<\/p>\n<p>For comprehensibility, allow me to quickly add a definition of the term palindrome:<\/p>\n<p class=\"has-global-color-8-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f4a1.png\" alt=\"\ud83d\udca1\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Definition<\/strong>: A palindrome is a sequence of characters that reads the same backward as forward such as <code>'madam'<\/code>, <code>'anna'<\/code>, or <code>'101'<\/code>.<\/p>\n<p>This article wants to give you a quick and easy solution in Python. First, we&#8217;ll solve the easier but important problem of checking if a substring is a palindrome in the first place:<\/p>\n<h2>How to Check If String is Palindrome<\/h2>\n<p>You can easily check if a string is a palindrome by using the <a href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" data-type=\"post\" data-id=\"731\">s<\/a><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" data-type=\"post\" data-id=\"731\" target=\"_blank\">l<\/a><a href=\"https:\/\/blog.finxter.com\/introduction-to-slicing-in-python\/\" data-type=\"post\" data-id=\"731\">icing<\/a> expression <code>word == word[::-1]<\/code> that evaluates to <code>True<\/code> if the word is the same forward and backward, i.e., it is a palindrome.<\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <strong>Recommended Tutorial<\/strong>: <a href=\"https:\/\/blog.finxter.com\/palindromes-in-one-line-python\/\" data-type=\"post\" data-id=\"3613\" target=\"_blank\" rel=\"noreferrer noopener\">Python Palindromes One-Liner<\/a><\/p>\n<p>Next, we&#8217;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):<\/p>\n<h2>Find All Substrings That Are Palindrome<\/h2>\n<p class=\"has-global-color-8-background-color has-background\">The brute-force approach to finding all palindromes in a string is to iterate over all substrings in a nested <code><a rel=\"noreferrer noopener\" href=\"https:\/\/blog.finxter.com\/python-loops\/\" data-type=\"post\" data-id=\"4596\" target=\"_blank\">for<\/a><\/code> loop. Then check each substring if it is a palindrome using <code>word == word[::-1]<\/code>. Keep track of the found palindromes using the <code><a href=\"https:\/\/blog.finxter.com\/python-list-append\/\" data-type=\"post\" data-id=\"6605\" target=\"_blank\" rel=\"noreferrer noopener\">list.append()<\/a><\/code> method. Return the final list after traversing all substrings.<\/p>\n<p>Here&#8217;s the full solution:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"7\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">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'))\n# ['l', 'o', 'oco', 'c', 'o', 'a', 'anna',\n# 'n', 'nn', 'n', 'a', 'ama', 'm', 'madam',\n# 'a', 'ada', 'd', 'a', 'm'] print(find_palindromes('anna'))\n# ['a', 'anna', 'n', 'nn', 'n', 'a'] print(find_palindromes('abc'))\n# ['a', 'b', 'c']<\/pre>\n<h2>Runtime Complexity<\/h2>\n<p>This has cubic runtime complexity, i.e., for a string with length <code>n<\/code>, we need to check <code>O(n*n)<\/code> different words. Each word may have up to <code>n<\/code> characters, thus the palindrome check itself is <code>O(n)<\/code>. Together, this yields runtime complexity of <code>O(n*n*n) = O(n\u00b3)<\/code>. <\/p>\n<h2>Quadratic Runtime Solutions<\/h2>\n<p>Is this the best we can do? No! There&#8217;s also an O(n\u00b2) time solution!<\/p>\n<p>Here&#8217;s a quadratic-runtime solution to find all palindromes in a given string that ignores the trivial one-character palindromes (significantly modified from <a rel=\"noreferrer noopener\" href=\"https:\/\/www.educative.io\/m\/find-all-palindrome-substrings\" data-type=\"URL\" data-id=\"https:\/\/www.educative.io\/m\/find-all-palindrome-substrings\" target=\"_blank\">source<\/a>):<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def find_palindromes(s, j, k): ''' Finds palindromes in substring between indices j and k''' palindromes = [] while j >= 0 and k &lt; 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'))\n# ['oco', 'nn', 'anna', 'ama', 'ada', 'madam'] print(find_all('anna'))\n# ['nn', 'anna'] print(find_all('abc'))\n# []\n<\/pre>\n<p>Feel free to join our community of ambitious learners like you (we have cheat sheets too): <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2764.png\" alt=\"\u2764\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (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 &#8216;madam&#8217;, &#8216;anna&#8217;, or &#8216;101&#8217;. This article wants [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-128100","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128100","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=128100"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/128100\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=128100"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=128100"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=128100"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}