Skip to content

Instantly share code, notes, and snippets.

@microamp
Created July 5, 2024 10:27
Show Gist options
  • Save microamp/6f0c6b9fa963a68bf7df0e5f0ffbcad9 to your computer and use it in GitHub Desktop.
Save microamp/6f0c6b9fa963a68bf7df0e5f0ffbcad9 to your computer and use it in GitHub Desktop.
Cute little palindrome tester with pattern matching in Python
def is_palindrome(s: str) -> bool:
def _is_palindrome(lst: list[str]) -> bool:
match lst:
case [x, *xs, y]:
return x == y and _is_palindrome(xs)
case _:
return True
return _is_palindrome(list(s))
assert is_palindrome("")
assert is_palindrome("a")
assert is_palindrome("aa")
assert is_palindrome("aba")
assert is_palindrome("abba")
assert not is_palindrome("ab")
assert not is_palindrome("abca")
assert not is_palindrome("abcdba")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment