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

found, index = search(myList, key)
                       if found:

                           print("Element",key," is present in the list at index ", index)
                       else:
                           print("Element",key," is not present in the list")
                       searchAgain = input("Continue another search? say Y/y for yes, N/n for no:")
                       if searchAgain != "Y" and searchAgain != "y":

                           break
               Program 16: Write a function search that takes a tuple myTuple and a value key to be searched in myTuple as
               arguments. When the key is present in myTuple, the function search returns True and the index where the
               search key is found. If search reaches the end of the tuple without finding the key, search returns False with
               None as the index. Invoke search to search for a key in a tuple provided by the user.


              Ans. def search(myTuple, key):
                       """
                       Objective: To search the key in myTuple
                       Input Parameters:
                           myTuple: tuple

                           key   : element to be searched
                       Return Value:
                           True: if key is found in the tuple, False otherwise
                           index:
                               if search succeeds, index of search key found

                               None, if search fails
                       """
                       found = False
                       for index in range(len(myTuple)):
                           if myTuple[index] == key:

                               found = True
                               return found, index
                       return found, None

                   myTuple = []

                   numElements = int(input("Enter size of the tuple: "))
                   print("Enter each element and press enter: ")
                   for i in range(0, numElements):   #tuple input element-wise
                       num = int(input())
                       myTuple += (num, )

                   print("Contents of tuple:", myTuple)
                   while True:
                       key = int(input("Enter the number to be searched:"))


               498   Touchpad Computer Science (Ver. 2.0)-XI
   507   508   509   510   511   512   513   514   515   516   517