From 59b015844dd4fdbd47ae32903f8fabaadc8aaa4a Mon Sep 17 00:00:00 2001 From: Drew Winstel Date: Wed, 29 May 2024 08:06:09 -0500 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=8D=20Use=20the=20stdlib=20for=20our?= =?UTF-8?q?=20score=20statistics?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Python 3.4 [introduced](https://docs.python.org/3/library/statistics.html) the `statistics` module into the standard library. Let's use that instead of calculating our own simply for the sake of not reinventing the wheel. --- grants/models.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/grants/models.py b/grants/models.py index 3ce4ce6..41e6897 100644 --- a/grants/models.py +++ b/grants/models.py @@ -1,5 +1,7 @@ from __future__ import annotations +from statistics import mean, variance, stdev + from django.db import models from urlman import Urls @@ -141,24 +143,19 @@ def average_score(self): scores = [s.score for s in self.scores.all() if s.score] if not scores: return None - else: - return sum(scores) / float(len(scores)) + return mean(scores) def variance(self): data = [s.score for s in self.scores.all() if s.score] - n = len(data) - if n == 0: - return 0 - c = sum(data) / float(len(data)) - if n < 2: + if not data: return 0 - ss = sum((x - c) ** 2 for x in data) - ss -= sum((x - c) for x in data) ** 2 / len(data) - assert not ss < 0, "negative sum of square deviations: %f" % ss - return ss / (n - 1) + return variance(data) def stdev(self): - return self.variance() ** 0.5 + data = [s.score for s in self.scores.all() if s.score] + if not data: + return 0 + return stdev(data) class Allocation(models.Model):