October 2018
Beginner to intermediate
466 pages
12h 2m
English
After writing a few small tests, we often find that we have to write the same setup code for several related tests. For example, the following list subclass has three methods for statistical calculations:
from collections import defaultdict
class StatsList(list):
def mean(self):
return sum(self) / len(self)
def median(self):
if len(self) % 2:
return self[int(len(self) / 2)]
else:
idx = int(len(self) / 2)
return (self[idx] + self[idx-1]) / 2
def mode(self):
freqs = defaultdict(int)
for item in self:
freqs[item] += 1
mode_freq = max(freqs.values())
modes = []
for item, value in freqs.items():
if value == mode_freq:
modes.append(item)
return modes
Clearly, we're going to want to test situations with each ...