Lec 13 BB
Lec 13 BB
Algorithms perform:
Calculation,
Data processing, and/or
Automated tasks.
Simple: Example
In this class, you’ll learn an algorithm-writing technique
called:
top-down design.
The sample data number of humpback whales seen on the coast of British Columbia
over the past ten years:
809 834 477 478 307 122 96 102 324 476
>>> counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
>>> low = min(counts)
>>> min_index = counts.index(low)
>>> print(min_index)
Summer code:
>>> counts = [809, 834, 477, 478, 307, 122, 96, 102, 324, 476]
>>> counts.index(min(counts))
Here are three high-level description.
Each is the first step in doing a top-down design solution.
Alg1:
1) Find, remove, find. Find the index of the minimum, remove that
item from the list, and find the index of the new minimum item
in the list. Then we find the second index.
3) Walk through the list. Examine each value in the list in order,
keep track of the two smallest values found so far, find their
indices.
While you are investigating these algorithms , consider this question:
Which one is the fastest?
In this step we start with the most obvious and clear comment, start
translating these comment into Python code:
Find smallest
Find index of smallest
Remove smallest
recall:
Remember that detailing the problem and writing the problem
specification are vital to the successful implementation of any
potential automated business/scientific process. In practice, arriving at
a well-defined problem specification is extremely important, and
very much possible that automated business project or processes
have failed in implementation due to an inadequate problem
specification.
Alg2-Step 1 of the top down design:
def find_two_smallest(L):
# Get a sorted copy of the list so that the two smallest items
# are at the front
def find_two_smallest(L):
""" (list of float) -> tuple of (int, int)
Return a tuple of the indices of the two smallest values in list L.
>>> find_two_smallest([809, 834, 477, 478, 307, 122, 96, 102, 324,
476])
(6, 7)
"""
# Examine each value in the list in order
# Keep track of the indices of the two smallest values found so far
# Update these values when a new smaller value is found
# Return the two indices
Alg3-step2:
We can call it before and after the code we want to time and take the
difference to find out how many seconds have elapsed.
EX: fid_time()
Next: find execution time for the three find_two_smallest
functions.
Rather than run the time individually for the three functions
1. create function whose parameters is the called function and the list