Last active
October 17, 2021 22:22
-
-
Save msyvr/435f7474cd82ae50e5fd3e69f492b085 to your computer and use it in GitHub Desktop.
mit 6.0001 - recursive check for palindrome
This file contains 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
def pal_rec(s): | |
''' | |
check if the alphabetical characters in a string read the same backwards and forewards | |
''' | |
# convert the input string to a list of lowercase alphanumeric characters only (i.e., punctuation, etc, omitted) | |
def to_char(s): | |
ls = list(s.lower()) | |
labc09 = list('abcdefghijklmnopqrstuvwxyz0123456789') | |
char_s = [i for i in ls if i in labc09] | |
return char_s | |
# check if each character is a match with its front-back 'mirror index' character | |
def pal_schar(char_s): | |
if len(char_s) <= 1: | |
return True | |
else: | |
return char_s[0] == char_s[-1] and pal_schar(char_s[1:-1]) | |
# return the Boolean result of the palindrome check applied to the (lowercase alphanumeric) string | |
return(pal_schar(to_char(s))) | |
if __name__ == "__main__": | |
s = input('Let\'s check for palindromes.\nWord or phrase:\n') | |
if pal_rec(s): | |
print(f'Yes, {s} is a palindrome') | |
else: | |
print(f'No, {s} is not a palindrome.') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment