So here is a code i have written to find palindromes within a word (To check if there are palindromes within a word including the word itself) Condition: spaces inbetween ch
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()
.