Python: search longest palindromes within a word and palindromes within a word/string
Solution 1:
Your solution seems a bit complicated to me. Just look at all of the possible substrings and check them individually:
def palindromes(text):
text = text.lower()
results = []
for i in range(len(text)):
for j in range(0, i):
chunk = text[j:i + 1]
if chunk == chunk[::-1]:
results.append(chunk)
return text.index(max(results, key=len)), results
text.index()
will only find the first occurrence of the longest palindrome, so if you want the last, replace it with text.rindex()
.
Solution 2:
The following function returns the longest palindrome contained in a given string. It is just slightly different in that it uses itertools
as suggested in this answer. There is value in abstracting away the combination generation. Its time complexity is evidently still cubic. It can trivially be adapted as needed to return the index and/or the list of palindromes.
import itertools
def longest_palindrome(s):
lp, lp_len = '', 0
for start, stop in itertools.combinations(range(len(s)+1), 2):
ss = s[start:stop] # substring
if (len(ss) > lp_len) and (ss == ss[::-1]):
lp, lp_len = ss, len(ss)
return lp