# ref: Zybooks Chapter 7.9 Lab: Palindrome # simple is_palindrome. Case sensitive, not removing any characters. def is_palindrome_1(s): """ Algorithm if s == reverse of s: return True else: return False if s == s[::-1]: return True else: return False """ return s == s[::-1] # using an alternative method. def is_palindrome_2(s): """ return s == reverse of s """ return s == "".join(list(reversed(s))) def is_palindrome_3(s): # case insensitive """ s to convertdc to lower case == reverse of s converted to lower case """ return s.lower() == s[::-1].lower() def remove_non_aphabet_chars(s): """ [1] whether a char is an alphabet. char.isalpha [2] remove those that are not alphabet. Algorithm: [1] result = '' [2] loop through char in s: if char is alphabet: result = result + char [3] return result """ result = '' for char in s: if char.isalpha(): result += char return result def is_palindrome_4(s): # case insensitive and remove non-alphabetic characters. """ [1] t <- remove non-alphabetic characters of s. [2] t.lower() == t[::-1].lower() """ t = remove_non_aphabet_chars(s) return t.lower() == t[::-1].lower() s1 = "racecar" s2 = "Racecar" s3 = "Hello world" s4 = "A Toyota's a Toyota." print(f"s1: {s1}") print(f"s2: {s2}") print(f"s3: {s3}") print(f"s4: {s4}") print(f"is_palindrome_1(s1): {is_palindrome_1(s1)}") print(f"is_palindrome_1(s2): {is_palindrome_1(s2)}") print(f"is_palindrome_1(s3): {is_palindrome_1(s3)}") print(f"is_palindrome_1(s4): {is_palindrome_1(s4)}") print(f"is_palindrome_2(s1): {is_palindrome_2(s1)}") print(f"is_palindrome_2(s2): {is_palindrome_2(s2)}") print(f"is_palindrome_2(s3): {is_palindrome_2(s3)}") print(f"is_palindrome_2(s4): {is_palindrome_2(s4)}") print(f"is_palindrome_3(s1): {is_palindrome_3(s1)}") print(f"is_palindrome_3(s2): {is_palindrome_3(s2)}") print(f"is_palindrome_3(s3): {is_palindrome_3(s3)}") print(f"is_palindrome_3(s4): {is_palindrome_3(s4)}") print(f"is_palindrome_4(s1): {is_palindrome_4(s1)}") print(f"is_palindrome_4(s2): {is_palindrome_4(s2)}") print(f"is_palindrome_4(s3): {is_palindrome_4(s3)}") print(f"is_palindrome_4(s4): {is_palindrome_4(s4)}")