Advertisement
Guest User

AverageStack.py

a guest
Jan 8th, 2012
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. from __future__ import division
  2.  
  3. class AverageStack:
  4.  
  5.     """Use it to smooth values over time.
  6.    
  7.    When you add a new value, the oldest value gets overwritten.
  8.    Returns the average of the remaining values.
  9.    
  10.    You can add any type as long as it supports __add__ in a numeric way.
  11.    Will return a float.
  12.    
  13.    """
  14.    
  15.    
  16.     def __init__(self, dim, default=0):
  17.    
  18.         """dim is the size of the stack: how many values to store
  19.        before starting to overwrite. default is the default value
  20.        the stack is filled with at start."""
  21.        
  22.         self._data = [default] * dim
  23.         self._pos = 0
  24.         self._dim = dim
  25.        
  26.        
  27.     def add(self, value):
  28.    
  29.         """Adds value to the stack and advances internal pointer."""
  30.        
  31.         self._data[self._pos] = value
  32.         self._pos += 1
  33.         if self._pos >= self._dim:
  34.             self._pos = 0
  35.  
  36.            
  37.     def avg(self, value=None):
  38.    
  39.         """Calculates the average of all values currently in stock.
  40.        This also includes the default values not yet overwritten.
  41.        You can add a value as the first parameter to add it to stack
  42.        before calculating the average."""
  43.        
  44.         if value is not None:
  45.             self.add(value)
  46.  
  47.         return sum(self._data) / self._dim        
  48.        
  49.        
  50.     def dump(self):
  51.    
  52.         """Just gets you some info for debugging."""
  53.        
  54.         print "data:" ,    
  55.         for i in range(self._dim):
  56.             print self._data[i] ,
  57.         print ""    
  58.         print " avg:" , self.avg()
  59.         print " pos:" , self._pos
  60.         print " dim:" , self._dim
  61.  
  62. # eof
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement