Skip to content

Instantly share code, notes, and snippets.

@davipatti
Last active October 29, 2025 17:25
Show Gist options
  • Select an option

  • Save davipatti/0829de9d8c9c9f9ff0ad31bed9420ac0 to your computer and use it in GitHub Desktop.

Select an option

Save davipatti/0829de9d8c9c9f9ff0ad31bed9420ac0 to your computer and use it in GitHub Desktop.
Finding palindromes, solution to Terry's little puzzle.
"""
# palindromes
See https://github.com/terrycojones/palindromes
"""
def substrings(s, l):
"""
generate length `l` substrings of `s`
"""
for i in range(len(s) + 1 - l):
yield s[i : i + l]
def find_palindromes(string):
# ignore non alphabetic chars and case
string = "".join(s for s in string.lower() if str.isalpha(s))
string_rev = "".join(reversed(string))
# check if substrings are in the reversed string
# check longer substrings first
for substring_length in reversed(range(1, len(string) + 1)):
if palindromes := {
substring
for substring in set(substrings(string, substring_length))
if substring in string_rev
}:
return palindromes
return {""}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment