In: Computer Science
Please provide Python code that does the following:
2) A palindrome is any sequence of characters that reads the same backwards as forwards. One-word examples include:
Dad |
madam |
rotor |
Kayak |
redder |
noon |
For the sake of this exercise, the following may also be considered one-word palindromes:
1881 |
zap4554paz |
That is, numeric strings and “nonsense” strings that read the same backwards as forwards should be classified as palindromes.
Write a program that takes as input a string and determines if it’s a one-word palindrome. Here’s a sample output.
Please enter a string: redder
redder is a palindrome.
Please enter a string: zap4554paz
zap4554paz is a palindrome.
Please enter a string: hello
hello is not a palindrome.
To check for one-word palindrome, start from beginning of the string till half the length of string and for each string character in the check if the same character is also at the corresponding place from the end of the string, that is, the first character should also be the last character, second character should be the second last character, and so on. If any check fails then it is not a palindrome.
Code:
# palindrome function
# returns true if a word is palindrome
def isPalindrome(s):
n = len(s)
# Run loop from 0 to half of length of string(exclusive).
# For even length string, loop is from 0 to length/2 - 1,
# as the string is zero indexed therefore,
# one of the two middle elements is at length/2 - 1
# If length of string is odd, then the middle element need not to
be concerned.
for i in range(0, int(n/2)):
if(s[i] != s[n-1-i]):
return
False
return True
# sample run
s = input("Please enter a string: ")
ans = isPalindrome(s)
if (ans):
print(s + " is a palindrome.")
else:
print(s + " is not a palindrome.")
Sample output:
Please take care of indentation in python. Attached code screenshot for your reference.