Page 366 - Computer Science V2.0 Class 11
P. 366

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))




               352   Touchpad Computer Science (Ver. 2.0)-XI
   361   362   363   364   365   366   367   368   369   370   371