Compare two window-total implementations

A vibration-analysis program needs the total acceleration reading in every complete window of 12 consecutive samples from a list of 240 samples. The following Python implementations calculate those window totals. You are comparing their computational cost, rather than interpreting the totals physically.


Use this simplified cost model: count only executions of the marked addition or subtraction in each implementation. Each marked operation costs one unit. Ignore indexing, assignment, loop control, list operations and all other arithmetic, including arithmetic inside range and indices. Python's range(a, b) includes a and excludes b.


Direct implementation


Python
n = 240
w = 12
window_totals = []
for start in range(n - w + 1):
    total = 0.0
    for j in range(start, start + w):
        total = total + samples[j]  # count this addition
    window_totals.append(total)


Prefix implementation


Python
n = 240
w = 12
prefix = [0.0]
for value in samples:
    prefix.append(prefix[-1] + value)  # count this addition
window_totals = []
for start in range(n - w + 1):
    total = prefix[start + w] - prefix[start]  # count this subtraction
    window_totals.append(total)


Find the direct implementation's operation count, the prefix implementation's operation count, and the ratio of the direct count to the prefix count. Give both counts as exact integers and the dimensionless ratio to two decimal places.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Programming Techniques for Data Analysis Questions: