Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import division
- class AverageStack:
- """Use it to smooth values over time.
- When you add a new value, the oldest value gets overwritten.
- Returns the average of the remaining values.
- You can add any type as long as it supports __add__ in a numeric way.
- Will return a float.
- """
- def __init__(self, dim, default=0):
- """dim is the size of the stack: how many values to store
- before starting to overwrite. default is the default value
- the stack is filled with at start."""
- self._data = [default] * dim
- self._pos = 0
- self._dim = dim
- def add(self, value):
- """Adds value to the stack and advances internal pointer."""
- self._data[self._pos] = value
- self._pos += 1
- if self._pos >= self._dim:
- self._pos = 0
- def avg(self, value=None):
- """Calculates the average of all values currently in stock.
- This also includes the default values not yet overwritten.
- You can add a value as the first parameter to add it to stack
- before calculating the average."""
- if value is not None:
- self.add(value)
- return sum(self._data) / self._dim
- def dump(self):
- """Just gets you some info for debugging."""
- print "data:" ,
- for i in range(self._dim):
- print self._data[i] ,
- print ""
- print " avg:" , self.avg()
- print " pos:" , self._pos
- print " dim:" , self._dim
- # eof
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement