Page 337 - Computer Science Class 11 With Functions
P. 337
(b) Searching for 10
Fig 13.1: Linear Search
Having understood the linear search algorithm, we are ready to develop a function linearSearch (see program 13.1)
that takes a list myList and a value key to be searched in myList as arguments. When the key is present in myList,
the function linearSearch returns True and the index where the search key is found. If linearSearch reaches
the end of the list without finding the key, linearSearch returns False with None as the index.
Program 13.1: Linear Search
01 def linearSearch(myList, key):
02 '''
03 Objective: To search the key in myList
04 Input Parameters:
05 myList: list
06 key : element to be searched
07 Return Value:
08 True: if key is found in the list, False otherwise
09 index:
10 if search succeeds, index of search key found
11 None, if search fails
12 '''
13 found = False
14 for index in range(len(myList)):
15 if myList[index] == key:
16 found = True
17 return found, index
18 return found, None
19
20 #main program segment
21 '''
22 Objective: To search for a key in a list
23 User Interface:
24 1.User is asked to enter a list
25 2. The user is asked to enter the key, and the program reports the search
26 result. This is repeated so long as the user wants to continue.
27 '''
28 myList = eval(input('Enter a list:\n'))
29 print('List:', myList)
30 while True:
31 key = int(input('Enter the number to be searched:'))
32 found, index = linearSearch(myList, key)
33 if found:
34 print(key,' is present in the list at index ', index)
35 else:
36 print(key,' is not present in the list')
37 searchAgain = input('Continue another search? say Y/y for yes, N/n for no:')
38 if searchAgain != 'Y' and searchAgain != 'y':
39 break
The result of executing Program 13.1 on a sample input list of size 15 is shown in Fig 13.1. The program begins by
creating an empty list myList. First, the user is prompted to enter a list of numbers.
Lists and Tuples 335

