Skip to content

Commit

Permalink
🐍 Use the stdlib for our score statistics (#20)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
drewbrew authored May 29, 2024
1 parent 1f3d564 commit e67d666
Showing 1 changed file with 9 additions and 12 deletions.
21 changes: 9 additions & 12 deletions grants/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from statistics import mean, variance, stdev

from django.db import models
from urlman import Urls

Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit e67d666

Please sign in to comment.