Skip to content

Instantly share code, notes, and snippets.

@glenrobertson
Created October 30, 2013 21:31
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 glenrobertson/7240658 to your computer and use it in GitHub Desktop.
Save glenrobertson/7240658 to your computer and use it in GitHub Desktop.
class MovingAverage:
total_sum = 0
total_count = 0
def add_number(self, num):
self.total_sum += num
self.total_count += 1
def get_average(self):
return self.total_sum / self.total_count
def reset(self):
self.total_sum = 0
self.total_count = 0
@glenrobertson
Copy link
Author

ma = MovingAverage()
ma.add_number(5)
ma.add_number(10)
# ... etc
ma.get_average()

@calcinai
Copy link

This isn't really a moving average though - same could be achieved with (psudo code, I don't know python)

class MovingAverage:
    average = None

    def add_number(self, num):
        if self.average is None:
            self.average = num
        else:
            self.average = (self.average + num) / 2

    def get_average(self):
        return self.average

    def reset(self):
        self.average = None

In this case not really worthy of a class...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment