Add some example code.
[pyutils.git] / src / pyutils / math_utils.py
index 97bb635ac7af5cb31a680338a87ffaecbb4adce5..6f042907d47764d34c2b83d3def98f41080058e8 100644 (file)
@@ -21,6 +21,8 @@ class NumericPopulation(object):
     >>> pop.add_number(1)
     >>> pop.add_number(10)
     >>> pop.add_number(3)
+    >>> len(pop)
+    3
     >>> pop.get_median()
     3
     >>> pop.add_number(7)
@@ -59,6 +61,15 @@ class NumericPopulation(object):
         if not self.minimum or number < self.minimum:
             self.minimum = number
 
+    def __len__(self):
+        """Return the population size."""
+        n = 0
+        if self.highers:
+            n += len(self.highers)
+        if self.lowers:
+            n += len(self.lowers)
+        return n
+
     def _rebalance(self):
         if len(self.lowers) - len(self.highers) > 1:
             heappush(self.highers, -heappop(self.lowers))
@@ -78,7 +89,7 @@ class NumericPopulation(object):
     def get_mean(self) -> float:
         """Returns the mean (arithmetic mean) so far in O(1) time."""
 
-        count = len(self.lowers) + len(self.highers)
+        count = len(self)
         return self.aggregate / count
 
     def get_mode(self) -> Tuple[float, int]:
@@ -122,7 +133,7 @@ class NumericPopulation(object):
         """
         if n == 50:
             return self.get_median()
-        count = len(self.lowers) + len(self.highers)
+        count = len(self)
         self._create_sorted_copy_if_needed(count)
         assert self.sorted_copy
         index = round(count * (n / 100.0))