X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=math_utils.py;h=156862a9c1b55eeec5515efef82f8f951d59b416;hb=89f305d67e913ea1512e2618a0375359ec925ada;hp=31610ba5fd2a0726b5b1f151dc87cc362b7389d4;hpb=14b42faebd598dc14cec6eaef77f06845e500b4b;p=python_utils.git diff --git a/math_utils.py b/math_utils.py index 31610ba..156862a 100644 --- a/math_utils.py +++ b/math_utils.py @@ -2,10 +2,13 @@ """Mathematical helpers.""" +import collections import functools import math from heapq import heappop, heappush -from typing import List, Optional +from typing import Dict, List, Optional, Tuple + +import dict_utils class NumericPopulation(object): @@ -25,7 +28,7 @@ class NumericPopulation(object): >>> pop.get_mean() 5.2 >>> round(pop.get_stdev(), 2) - 6.99 + 1.75 >>> pop.get_percentile(20) 3 >>> pop.get_percentile(60) @@ -70,6 +73,14 @@ class NumericPopulation(object): count = len(self.lowers) + len(self.highers) return self.aggregate / count + def get_mode(self) -> Tuple[float, int]: + count: Dict[float, int] = collections.defaultdict(int) + for n in self.lowers: + count[-n] += 1 + for n in self.highers: + count[n] += 1 + return dict_utils.item_with_max_value(count) + def get_stdev(self) -> float: """Returns the stdev so far in O(n) time.""" @@ -80,7 +91,8 @@ class NumericPopulation(object): variance += (n - mean) ** 2 for n in self.highers: variance += (n - mean) ** 2 - return math.sqrt(variance) + count = len(self.lowers) + len(self.highers) - 1 + return math.sqrt(variance) / count def get_percentile(self, n: float) -> float: """Returns the number at approximately pn% (i.e. the nth percentile)