Page 356 - Computer Science Class 11 With Functions
P. 356

36     else:
          37         print('Element',key,' is not present in the tuple')
          38     searchAgain = input('Continue another search? say Y/y for yes, N/n for no:')
          39     if searchAgain != 'Y' and searchAgain != 'y':
          40         break

        Sample Output:
         >>> Enter a tuple:
              (4,5,2,3,4)
              Contents of Tuple: (4, 5, 2, 3, 4)
         >>> Enter the number to be searched: 4
              Element 4 is present in the tuple at index 0
              Continue another search? say Y/y for yes, N/n for no:y
         >>> Enter the number to be searched: 2
              Element 2 is present in the tuple at index 2
              Continue another search? say Y/y for yes, N/n for no:y
         >>> Enter the number to be searched: 10
              Element 10 is not present in the tuple
              Continue another search? say Y/y for yes, N/n for no:n
        5.   Write a function to count the frequency of each element in a tuple. Write a program that accepts a tuple of
            integers and displays the count of frequency of each element in the tuple.
          01 def countFrequency(myTuple):
          02     '''
          03     Objective: To count the frequency of each element in myTuple
          04     Input Parameters:
          05         myTuple: tuple
          06     Return Value:
          07         frequency: A list comprising (key, frquency) tuples
          08     '''
          09     frequency = []
          10     uniqueMyTuple = set(myTuple)
          11     for item in uniqueMyTuple:
          12         frequency.append((item, myTuple.count(item)))
          13     return frequency
          14
          15 #main program segment
          16 '''
          17 Objective: To count the frequency of each element in myTuple
          18 User Interface:
          19     User is asked to enter:
          20       number of elements in the tuple
          21       tuple elements one by one
          22 '''
          23 myTuple = eval(input('Enter a tuple\n'))
          24 print('Tuple:', myTuple)
          25 frequency = countFrequency(myTuple)
          26 for tpl in frequency:
          27     print(f'Count of {tpl[0]} in tuple is: {tpl[1]}')
        Sample Output:
         >>> Enter a tuple
              (1,2,3,2,3,5)
              Tuple: (1, 2, 3, 2, 3, 5)
              Count of 1 in tuple is: 1
              Count of 2 in tuple is: 2
              Count of 3 in tuple is: 2
              Count of 5 in tuple is: 1

         354   Touchpad Computer Science-XI
   351   352   353   354   355   356   357   358   359   360   361