Respuesta :
Answer:
The solution code is written in Python 3.
- import math
- def processString(myStr):
- process = myStr.lower()
- process = process.replace(" ","")
- p_list = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
- for p in p_list:
- process = process.replace(p, "")
- return process
- def isPalindrome(myStr):
- myStr = processString(myStr)
- for i in range(0, math.ceil(len(myStr))):
- lastIndex = len(myStr) - 1 - i
- if(myStr[0] != myStr[lastIndex]):
- return False
- return True
- print(isPalindrome("racecar"))
- print(isPalindrome("apple"))
- print(isPalindrome("Was it a car or a cat I saw?"))
- print(isPalindrome("No 'x' in Nixon"))
- print(isPalindrome("Programming is fun!"))
Explanation:
Since the palindrome function is expected to work on a sentence, we need to process the string prior to checking if the string is a palindrome. To process a string, a separate function is written, processString() with one parameter, "myStr" that will accept one input string. (Line 3 - 11)
Within the processString() function, there are three processing steps on the input string, my_str:
- convert all letters in string to lowercase using Python string lower() method (Line 4)
- remove all word dividers (Line 5) using replace() method
- remove all punctuation (Line 7-9). To remove punctuation, we need to define a punctuation list (Line 7). Next, use for-loop to traverse the punctuation list and whenever there is a punctuation appears in the input string, remove it using replace() method (Line 8-9).
After the function processString() is ready, we can proceed to work on the palindrome function, isPalindrome(). This function has one parameter that will accept one input string.
Within the function isPalindrome(), we call the function processString by passing the input string, my_str as argument (Line 14). The function processString() will operate on the my_str by converting all the letters to lowercase, removing all the word dividers and punctuation.
Next the processed string will be returned to my_str. Next, within a for-loop, traverse through the letters in my_str and compare the first letter with the last letter, second letter with second last letter until it reaches the middle point. (Line 15-17) If any comparison is found unmatched, return false since it is not a palindrome. If there is no unmatched found in the for-loop, the function will just return true.
At last, we test our function isPalindrome() with several test strings (Line 22 26) and the output is as follows:
True
False
True
True
False