Lecture 20 — Exercises¶
Solutions to the problems below must be sent to Submitty for automatic scoring. A separate file must submitted for each problem.
For both of these exercises download the file lec20_ex.zip
from
the Course Materials page on Submitty. 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_search
that is given two arguments: a valuex
and a listL
. The function must return the list index of the first location ofx
inL
. Ifx
is not inL
the function must return -1. You may use any Pythonlist
functions you wish. Submit the modifiedlec20_ex_start.py
as your Part 1 solution.What if the list is already sorted? Write a modifed version of
linear_search
that returns the index of the first instance ofx
or the index wherex
should be inserted if it is not inL
For example, in the listL = [ 1.3, 7.9, 11.2, 15.3, 18.5, 18.9, 19.7 ]
the call
linear_search(11.9, L)
should return 3, while the call
linear_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
for
or awhile
loop. Submit the modifiedlec20_ex_start.py
as your Part 2 solution.