Lecture 20 — Exercises¶
Solutions to the problems below must be sent to Submitty for automatic scoring. A separate file must submitted for each problem. Solutions must be submitted by 4 pm on Tuesday, November 15.
For both of these exercises download the file
the course Piazza Resource page. It includes a data file and
lec20_ex_start.py. You start from the latter for both exercises.
You will notice that the main code in this file requests the name of a
data file from the user, opens and reads the file to form a list of
values, and then in a loop requests several different values to search
for, outputting the result of the function call for each.
- Write a Python function called
linear_searchthat is given two arguments: a value
xand a list
L. The function must return the list index of the first location of
xis not in
Lthe function must return -1. You may use any Python
listfunctions you wish.
- What if the list is already sorted? Write a modifed version of
linear_searchthat returns the index of the first instance of
xor the index where
xshould be inserted if it is not in
LFor example, in the listL = [ 1.3, 7.9, 11.2, 15.3, 18.5, 18.9, 19.7 ]
the calllinear_search(11.9, L)
should return 3, while the calllinear_search( 20.5, L)
should return 7. You must not use binary search (even though that would be faster — this is an exercise) and you must use either a