In: Computer Science
6. Write a Python function that checks whether a passed string is palindrome or
not. Note:-A palindrome is a word, phrase, or sequence that reads the same backward
as forward
. Some examples you may try: “madam”
redder
“race car”
Eva, Can I Stab Bats In A Cave?
If the argument passed is not a string,
invoke an exception or an assertion
and state in a comment which one you have chosen and why.
Step-1) check if the passed input is of type str or not .If input is not of type str raise TypeError showing input must be of type str.
we should raise the exception to make user aware of his wrong input as early as possible.It is always better to detect error as early as possible in programming to avoid useless computations.
step-2)form a string of alphabets to avoid special characters and spaces in the text.
Step-3)If every ith character is same from beginning and end of the string , than we can say that the string is a palindrome.
Code:
def check_palindrome(string): # raise a TypeError if the passed input is not of str type if not isinstance(string, str): raise TypeError("Input must be of type String") else: # first form a string of alphabets from a given input string final_string = "" for char in string: if char.isalpha(): # returns true if the character is an alphabet final_string += char.upper() # converts the alphabet to uppercase n = len(final_string) # final_string[i] gives the ith character from start and final_string[n-i-1] gives the ith string from end for i in range(0, n // 2): if final_string[i] == final_string[n - i - 1]: continue else: return "given input is not a palindrome" return "given input is a palindrome" if __name__ == '__main__': # main method for testing out the above method print(check_palindrome("race car"))
If you have any doubt in understanding the solution or want any modification in code , just put a comment on the answer and i would be happy to help you out.