A statistical list

It makes good sense to incorporate mean and standard deviation features directly into a subclass of list. We can extend list like this:

class StatsList(list):

def __init__(self, iterable: Optional[Iterable[float]]) -> None:
super().__init__(cast(Iterable[Any], iterable))

@property
def mean(self) -> float:
return sum(self) / len(self)

@property
def stdev(self) -> float:
n = len(self)
return math.sqrt(
n * sum(x ** 2 for x in self) - sum(self) ** 2
) / n

With this simple extension to the built-in list class, we can accumulate data and report statistics on the collection of data items.

Note the relative complexity involved in narrowing the type of the list class. The built-in list structure's type, List, is effectively List[Any]. In order for the arithmetic operations to work, the content really must be List[float]. By stating the __init__() method will only accept an Iterable[float] value, mypy is forced to confirm arguments to StatsList will meet this criteria. Let's imagine we have a source of raw data:

def data_gen() -> int:
return random.randint(1, 6) + random.randint(1, 6)

This little data_gen() function is a stand-in for a variety of possible functions. It might be a complex simulation. It might be a source of actual measurements. The essential feature of this function—defined by the type hint—is to create an integer value.

We can imagine that an overall simulation script can use the StatsList class, as follows:

random.seed(42)
data = [data_gen() for _ in range(100)]
stats = StatsList(data)
print(f"mean = {stats.mean:f}")
print(f"stdev= {stats.stdev:.3f}")

This snippet uses a list comprehension to create a raw list object with 100 samples. Because the data object is built from the data_gen() function, it's clear that the data object has the type List[int]From this, a StatsList object is created. The resulting stats object has mean and stdev properties, which are extensions to the base list class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset