Skip to content

Instantly share code, notes, and snippets.

@sumoward
Created May 22, 2016 13:42
Show Gist options
  • Save sumoward/d1060638f4e3c1cfdf9bbde9385c4d6b to your computer and use it in GitHub Desktop.
Save sumoward/d1060638f4e3c1cfdf9bbde9385c4d6b to your computer and use it in GitHub Desktop.
"""
make the loop go through each character in the text,
and see if you've got a palindrome when extending with the left and right character of your current character.
This way you'll stop checking when it's not a palindrome and don't waste time checking non-palindromes.
"""
DEFAULT_TEXT = "racecarenterelephantmalayalam"
def all_palindromes(text=DEFAULT_TEXT):
"""Return list with all palindrome strings within text.
The base of this algorithm is to start with a given character,
and then see if the surrounding characters are equal. If they
are equal then it's a palindrome and is added to results set,
extend to check if the next character on either side is equal,
adding to set if equal, and breaking out of loop if not.
This needs to be repeated twice, once for palindromes of
odd lengths, and once for palindromes of an even length."""
results = set()
text_length = len(text)
for index, character in enumerate(text):
# Check for longest odd palindrome(s)
start, end = index - 1, index + 1
while start >= 0 and end < text_length and text[start] == text[end]:
new_text = text[start:end + 1]
print(new_text)
results.add(new_text)
start -= 1
end += 1
# Check for longest even palindrome(s)
start, end = index, index + 1
while start >= 0 and end < text_length and text[start] == text[end]:
results.add(text[start:end + 1])
start -= 1
end += 1
return list(results)
def main(text=DEFAULT_TEXT):
print(all_palindromes(text))
if "__main__" == __name__:
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment