Place these files in a lab4 folder. Before leaving lab, zip up the lab4 folder and hand in the zip file.
Note: The search and timer functions below should be put in the file search_timing.py
Creating a list containing a range of elements
list(range(0, 10)) (not needed today, but note that [elem] * N replicates a single value)
def search(integer_list, key): for i in range(0, len(integer_list)): if integer_list[i] == key: return i return None
import time def timer(): start = time.time() """ insert the code to be timed here, e.g. search(list, key) Make sure to remove the quote marks! """ end = time.time() return end - start
Create a list whose elements contain the integers from 100,000 through 300,000, inclusive (be careful! what should the range be?) and set the variable big_list to contain that list.
NOTE: Put the assignment that creates big_list in your python file outside the scope of a function. Do NOT assign to big_list in the timer or search functions because it will invalidate the timing and search results.
Time how long it takes the search function above to find each of the following in big_list:
How long does each take?
If you repeat the same searches, does it take exactly the same amount of time? Why do you think this is?
How would you describe the relationship between the position of the item you are searching for in the list and how long it takes to find that item? (Is the search time independent of the position, or is there some mathematical relationship between the two quantities?)
Write your answers in a text file called timings.txt.
In is_all_odd.py, write a Python function is_all_odd(integer_list) that takes an integer list as an argument and returns True if all the elements in the list are odd numbers and False otherwise. (Hint: how is this different from the function search(integer_list, key) given above?)
Example:
>>> 4 % 2 0 >>> 5 % 2 1 >>> is_all_odd([1, 2, 8, 12, 99]) False >>> is_all_odd([1, 3, 5, 7]) True >>> is_all_odd([]) True
Example Output: >>>listA = ["cat", "bat", "car", "dog", "spat"] >>>string_search(listA, "a") [ 'cat', 'bat', 'car', 'spat' ] >>>string_search(listA, "at") [ 'cat', 'bat', 'spat' ] >>>string_search(listA, "l") []