Last active
October 29, 2025 17:25
-
-
Save davipatti/0829de9d8c9c9f9ff0ad31bed9420ac0 to your computer and use it in GitHub Desktop.
Finding palindromes, solution to Terry's little puzzle.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| # 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