Back

A serial search program from the algorithm

We have seen that a typical algorithm for a serial search through a list called myList of size n to find the first instance of a piece of data is as follows:

Set a variable called index = 0    # this will be our counter, to work through a list
Set a Boolean flag called found = False    # this will indicate if we have found the item or not
Set a variable called hunted to be the data we are searching for.

while (index < n) and (found == false):
     if myList[index] == hunted
        found = true
     else
         index = index + 1

if found == true
     print("Item found at position", index)
else
     print("Item not found.")

Q1. Type the following code into Python and get it working.

serial1

The top part should be familar to you from earlier lessons. We simply generate a list or random numbers and write a function we can use to print out the list at any time. We generate our list, then ask the user what number they want to search for. We then search for it using the code, which is based directly on the algorithm. We either return the position of the forst instance of the data we are looking for or we return 'Item not found'.

Q2. Try out the following inputs when you run the code. Before you run each test, try and predict what should happen.

20 items in the list and search for 5.
20 items in the list and search for 35.
0 items in the list and search for 3.
0 items in the list and search for 64.

Q3. Try altering the program slightly:

Try generating a smaller range of numbers and running some tests with different inputs.
Try generating a larger range of numbers and running some tests with different inputs.  

Extension task
Modify your program so that it asks the user for an animal and then searches through a list of animals.

Back