Page 319 - Computer Science Class 11 With Functions
P. 319
Solved Programming Question
A string is a palindrome if it reads the same from both ends, for example, 'madam', 'rotator', 'level',
'abcde0edcba'. Write a function palindrome(string) to check whether a given string is a palindrome.
Write a program that takes a string as input from a user and makes use of the function palindrome() to print an
appropriate message depending on whether the input string is a palindrome.
def palindrome(string):
'''
Objective: To check whether the given string is a palindrome.
Input Parameter: string – a Python string
Return Value: True if string is a palindrome, False otherwise.
'''
'''
Approach:
For each position i in string, check if elements at i and len(string)-(i-1) th
locations are the same. If this holds true for all i in range [1, len(string)/2]
return True else False.
'''
n = len(string)
if n == 0: #null string
return True
else:
j = n-1 #index of the rightmost character
for i in range(n//2+1):
if string[i] != string[j]:
return False #character mismatch
j -= 1
return True
'''
Objective: To check whether the given string is a palindrome
Input parameter: None
Return value: None
'''
'''
Approach: To use function palindrome
'''
myString = input('Enter a string to check:')
if palindrome(myString):
print("String '%s' is a Palindrome" %(myString))
else:
print("String '%s' is not a Palindrome" %(myString))
Strings 317

