67 lines
2.5 KiB
Python
Executable File
67 lines
2.5 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# palindrome - check palindromes and find the longest palindromic substring
|
|
# Usage: palindrome "TEXT" [--longest] | palindrome --selftest
|
|
import argparse, sys
|
|
|
|
def normalize(s):
|
|
return "".join(c.lower() for c in s if c.isalnum())
|
|
|
|
def is_palindrome(s):
|
|
n = normalize(s)
|
|
return len(n) > 0 and n == n[::-1]
|
|
|
|
def longest_palindromic_substring(s):
|
|
# Expand-around-centre on the NORMALIZED string (alphanumerics only,
|
|
# lowercased), so "A man, a plan, a canal: Panama" correctly yields
|
|
# the full 21-char palindrome instead of a 3-char raw fragment.
|
|
# O(n^2) time, O(1) extra space.
|
|
s = normalize(s)
|
|
if not s:
|
|
return ""
|
|
best = s[0]
|
|
def expand(lo, hi):
|
|
while lo >= 0 and hi < len(s) and s[lo].lower() == s[hi].lower():
|
|
lo -= 1; hi += 1
|
|
return s[lo + 1:hi]
|
|
for i in range(len(s)):
|
|
for cand in (expand(i, i), expand(i, i + 1)):
|
|
if len(cand) > len(best):
|
|
best = cand
|
|
return best
|
|
|
|
def selftest():
|
|
assert is_palindrome("racecar")
|
|
assert is_palindrome("A man, a plan, a canal: Panama")
|
|
assert is_palindrome("No 'x' in Nixon")
|
|
assert not is_palindrome("hello")
|
|
assert not is_palindrome("")
|
|
assert longest_palindromic_substring("babad") in ("bab", "aba")
|
|
assert longest_palindromic_substring("cbbd") == "bb"
|
|
assert longest_palindromic_substring("racecar") == "racecar"
|
|
assert longest_palindromic_substring("forgeeksskeegfor") == "geeksskeeg"
|
|
assert longest_palindromic_substring("A man, a plan, a canal: Panama") == "amanaplanacanalpanama"
|
|
print("palindrome selftest OK")
|
|
|
|
def main():
|
|
p = argparse.ArgumentParser(description="Check palindromes and find the longest palindromic substring.")
|
|
p.add_argument("text", nargs="*", help="text to check")
|
|
p.add_argument("--longest", action="store_true", help="also print the longest palindromic substring")
|
|
p.add_argument("--selftest", action="store_true", help="run a built-in self-test and exit")
|
|
a = p.parse_args()
|
|
if a.selftest:
|
|
selftest(); return 0
|
|
if not a.text:
|
|
p.error("give text to check")
|
|
text = " ".join(a.text)
|
|
if is_palindrome(text):
|
|
print(f"'{text}' IS a palindrome.")
|
|
else:
|
|
print(f"'{text}' is NOT a palindrome.")
|
|
if a.longest or True:
|
|
longest = longest_palindromic_substring(text)
|
|
print(f"Longest palindromic substring: '{longest}' ({len(longest)} chars)")
|
|
return 0
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|