If every basic operation costs one unit, why does a nested loop cost 3n² + n + 1 rather than just 3n²?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
The video prices c*9.0/5 + 32 at 3 units of time, one unit for each basic operation in it. Count the operations in the body of this function the same way:
def poly(x): return 2*x*x + 5*x + 1
Assign the number of basic operations to ops.
One unit of time per basic operation
List the operations that each count as one unit - arithmetic, comparison, assignment, accessing an object in memory - and record that a program's cost is written in terms of its input, not seconds.
Constant cost of c_to_f
Write the three operations of the conversion - a multiplication, a division and an addition - and record that the count stays three for any input.
The hand counts and
Trace mysum and square line by line, tallying the initial assignment, the loop's own assignment of i, and the two operations of total += i, times the number of passes.
Counter variables in the rewritten functions
Write each function again with a counter that increments where the operations happen and returns (counter, value) as a tuple, and match the tallies against the hand counts.