Skip to content

Instantly share code, notes, and snippets.

@joshspicer
Created March 25, 2020 12:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshspicer/9f0ee44a8ece24ba97ec1f49510e7393 to your computer and use it in GitHub Desktop.
Save joshspicer/9f0ee44a8ece24ba97ec1f49510e7393 to your computer and use it in GitHub Desktop.
Demonstrates calculating running average without maintaining a list of past values.
#!/usr/bin/env python3
"""
Demonstrates calculating running average without maintaining a list of past values.
"""
nums = [55,2,591,5,31,73,7823,8,11,952,4,75,2,1000,1]
def classic_average():
avg = sum(nums) / len(nums)
print("The classic average is {}".format(avg))
def running_average():
n = 0
running_avg = 0
for num in nums:
n += 1
running_avg = running_avg + ((num - running_avg) / n)
print("The running average is {}".format(running_avg))
classic_average()
running_average()
"""
Output:
The classic average is 708.8666666666667
The running average is 708.8666666666667
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment