Serial search - Answers
Here are the two programs that students were ask to get working. You can copy and paste them straight into Python.
Searching through a list of numbers
import random
#This code creates a list of random numbers
myList = [] # create an empty list
size = int(input('How many data items? >>> ')) # ask for the size required
for i in range(size): # for i= 0 to (size-1)
myList.append(random.randint(1,10)) # get a random number and append it to the list
#This function prints out the list.
def printList(anyList):
for i in range(len(anyList)): # for i= 0 to (size-1)
print(anyList[i],end=' ')
print('\n')
hunted = int(input("What number do you want to search for? >>> "))
printList(myList)
index = 0
found = False
while (index < len(myList)) and (found == False):
if (myList[index] == hunted):
found = True
else:
index = index + 1
if (found == True):
print("Item found at position",index) # remember to count from position 0 !!
else:
print("Item not found.")
Searching a list of animals
myList=["adder", "zebra", "lion", "rat", "koala bear", "monkey", "shark", "ant"]
#This function prints out the list.
def printList(anyList):
for i in range(len(anyList)): # for i= 0 to (size-1)
print(anyList[i],end=' ')
print('\n')
hunted = input("What animal do you want to search for? >>> ")
printList(myList)
index = 0
found = False
while (index < len(myList)) and (found == False):
if (myList[index] == hunted):
found = True
else:
index = index + 1
if (found == True):
print("Item found at position",index) # remember to count from position 0 !!
else:
print("Item not found.")