2

I have a statistics.py file which has some methods for the class Statistics. Here is how it looks:

class Statistics(object):
    def __init__(self):
        self.__count = 0      # how many data values seen so far
        self.__avg = 0        # the running average so far

    def add(self, value):
        self.__count += 1      
        diff = value - self.__avg  # convenience
        self.__avg += diff / self.__count

    def mean(self):
        return self.__avg

    def count(self):
        return self.__count

I need to add two more methods to this

  1. maximum() which returns the maximum value ever recorded by the Statistics object and none if no values are seen.
  2. minimum() which returns the minimum value ever recorded by the Statistics object and none if no values are seen.

I tried using max() and min() functions couldn't include them properly. Any help where I can rectify my mistake? Here is how that looked:

class Statistics(object):
    def __init__(self):
        self.__count = 0      # how many data values seen so far
        self.__avg = 0        # the running average so far
        self.__max= 0
        self.__max=max(value)


    def add(self, value):
        self.__count += 1      
        diff = value - self.__avg  # convenience
        self.__avg += diff / self.__count


    def mean(self):
        return self.__avg

    def count(self):
        return self.__count
        
    def maximum(self):
        return self.__max
ppwater
  • 2,315
  • 4
  • 15
  • 29

1 Answers1

1

Do the same thing that you do for self.__avg but instead for a self.__max / self.__min - keep the current max/min in a instance variable.

On adding a new value via self.add(..) check if the new value is bigger as your current and set your self.__max - do the same for minimal value.

You can init your instance variables to None to start with.

class Statistics(object):
    def __init__(self):
        self.__count = 0      # how many data values seen so far
        self.__avg = 0        # the running average so far
        self.__max = None
        self.__min = None


    def add(self, value):
        self.__count += 1
        diff = value - self.__avg  # convenience
        self.__avg += diff / self.__count
        
        self.__max = value if self.__max is None else max(self.__max, value)
        self.__min = value if self.__min is None else min(self.__min, value)


    def mean(self):
        return self.__avg

    def count(self):
        return self.__count
    
    def maximum(self):
        return self.__max

    def minimum(self):
        return self.__min

Test:

s = Statistics()

print(s.maximum(), s.minimum(), s.mean()) 

s.add(42)
s.add(11)
s.add(-13)
s.add(142)
s.add(99)

print(s.maximum(), s.minimum(), s.mean())

Output:

None None 0
142 -13 56.2

See Does Python have a ternary conditional operator? for what self.__max = value if self.__max is None else max(self.__max, value) does.

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69