Skip to content

Instantly share code, notes, and snippets.

@obriencj obriencj/average.py
Last active Jul 6, 2019

Embed
What would you like to do?
example rolling average class in python
class RollingAverage(object):
def __init__(self, values=(), start_sum=0, start_count=0):
self._sum = start_sum + sum(values)
self._count = start_count + len(values)
def append(self, value):
self._sum += value
self._count += 1
def extend(self, values):
self._sum += sum(values)
self._count += len(values)
def clear(self):
self._sum = 0
self._count = 0
@property
def average(self):
return self._sum / (self._count or 1)
@property
def total(self):
return self._sum
@property
def count(self):
return self._count
def __float__(self):
return self.average
def __int__(self):
return int(self.average)
def __str__(self):
return str(self.average)
def __eq__(self, other):
return self.average == other
def __ne__(self, other):
return self.average != other
def __gt__(self, other):
return self.average > other
def __lt__(self, other):
return self.average < other
def __ge__(self, other):
return self.average >= other
def __le__(self, other):
return self.average <= other
def __repr__(self):
return "<rolling average of %i items: %r>" % \
(self._count, self.average)
#
# The end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.