Page 273 - Computer Science Class 11 Without Functions
P. 273

11.6.4 Constructing the Reverse of a Given String

            Let us develop a program that takes a string as an input from the user.
            ●  Next, we initialize the string comprising characters in reverse order (revString) to an empty string (line 9).
            ●  Next, we scan the string and append every subsequent letter to the beginning of the revString (lines 11-12).

            ●  Finally, output the reversed string (revString) (line 14).

            Program 11.4 Constructing the reverse of a string
              01 '''
              02 Objective: To reverse the given string
              03 Input: string - string value
              04 Output: string with the characters of the string reversed
              05 '''
              06
              07 string = input('Enter a string: ')
              08
              09 revString = ''
              10 lengthSubstr = len(string)
              11 for char in string:
              12     revString = char + revString
              13
              14 print('Reverse of ', string, ' is:',revString)
            Solved Programming Question

                  A string is a palindrome if it reads the same from both ends, for example, 'madam', 'rotator', 'level',
                'abcde0edcba'.  Write a program  to check whether a given string is a palindrome. The program takes a
                string as input from a user and makes prints an appropriate message depending on whether the input string is a
                palindrome.
            Ans. Objective: To check whether the given string is a palindrome.
                Input: string – a Python string
                Output: Appropriate message when string is a palindrome and when it is not.
                '''

                '''
                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.
                '''

                myString = input('Enter a string to check:')

                n = len(myString)
                flag = True

                if n == 0: #null string
                    flag = True
                else:
                    j = n-1 #index of the rightmost character
                    for i in range(n//2+1):
                        if myString[i] != myString[j]:
                            flag = False #character mismatch
                        j -= 1

                                                                                                       Strings   271
   268   269   270   271   272   273   274   275   276   277   278