LearnFrenzy
Sign in Take a free test

Lists · Lists Coding Problems · Question 8

Running total and 3-day moving average in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

For daily sales, print the running (cumulative) total and the 3-day moving average.

Solution
main.py Run
sales = [120, 90, 150, 80, 200, 170]

running, total = [], 0
for s in sales:
    total += s
    running.append(total)

moving = [round(sum(sales[i - 2:i + 1]) / 3, 1) for i in range(2, len(sales))]

print("Running:", running)
print("3-day avg:", moving)

Output Verified by running it on Python 3

Running: [120, 210, 360, 440, 640, 810]
3-day avg: [120.0, 106.7, 143.3, 150.0]

The slice sales[i - 2:i + 1] is a window of three days ending at day i. itertools.accumulate(sales) also gives the running total.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links