How does counting operations turn a stopwatch reading into a formula, and how can a running program count its own operations?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Here is a function that converts Fahrenheit to Celsius:
def f_to_c(f): shifted = f - 32 return shifted * 5 / 9
Count the primitive operations one call to f_to_c performs, treating each arithmetic operation and each assignment as one unit. Assign the count under this lecture's rules, where the return counts as an operation too, to ops_now, and the count under last lecture's rules, where it does not, to ops_before.
Primitive operations as one constant unit each
List the operations counted as one unit each (arithmetic, comparison, indexing, assignment and, newly, return) and record that the result is a formula in input size whose constant depends on this choice.
Hand counts for convert_to_km and sum_of
Trace both functions line by line, marking the per-iteration cost inside the loop, to reach 2 operations for convert_to_km whatever its input and 3 * len(L) + 2 for sum_of.
Instrumenting a function with a global counter
Write is_in_counter and binary_search_counter with global count and their count += lines, annotate which operations each increment accounts for, and note that globals are bad practice outside counting or debugging.
Counted growth of linear versus binary search
Copy a few rows of both count tables, record that is_in's count multiplies by ten per tenfold input while binary search's merely adds 70 to 100, and note the linear and logarithmic plot shapes.