ahmet / Python-for-Data-Science
Herkese Açık Ahmet Kerem Piscine Final
statistics.py 2.5 KB
from typing import Any
def ft_mean(values: list) -> float:
"""Return the mean of a non empty list of numbers."""
return sum(values) / len(values)
def ft_median(values: list) -> float:
"""Return the median of a non empty list of numbers."""
ordered = sorted(values)
middle = len(ordered) // 2
if len(ordered) % 2:
return ordered[middle]
return (ordered[middle - 1] + ordered[middle]) / 2
def ft_percentile(values: list, percent: float) -> float:
"""Return a percentile, between 0 and 1, by linear interpolation."""
ordered = sorted(values)
position = percent * (len(ordered) - 1)
lower = int(position)
upper = min(lower + 1, len(ordered) - 1)
weight = position - lower
return float(ordered[lower] + (ordered[upper] - ordered[lower]) * weight)
def ft_quartile(values: list) -> list:
"""Return the 25% and 75% quartiles of a list of numbers."""
return [ft_percentile(values, 0.25), ft_percentile(values, 0.75)]
def ft_var(values: list) -> float:
"""Return the variance of a non empty list of numbers."""
mean = ft_mean(values)
return sum((value - mean) ** 2 for value in values) / len(values)
def ft_std(values: list) -> float:
"""Return the standard deviation of a non empty list of numbers."""
return ft_var(values) ** 0.5
def ft_statistics(*args: Any, **kwargs: Any) -> None:
"""Print the statistics of args asked by the values of kwargs.
An unknown operation is ignored, a computation that cannot be
done prints ERROR.
"""
operations = {
"mean": ft_mean,
"median": ft_median,
"quartile": ft_quartile,
"std": ft_std,
"var": ft_var,
}
for wanted in kwargs.values():
if wanted not in operations:
continue
try:
print(f"{wanted} : {operations[wanted](list(args))}")
except Exception:
print("ERROR")
def main() -> None:
"""Test the statistics on several sets of arguments."""
ft_statistics(1, 42, 360, 11, 64,
toto="mean", tutu="median", tata="quartile")
print("-----")
ft_statistics(5, 75, 450, 18, 597, 27474, 48575,
hello="std", world="var")
print("-----")
ft_statistics(5, 75, 450, 18, 597, 27474, 48575,
ejfhhe="heheh", ejdjdejn="kdekem")
print("-----")
ft_statistics(toto="mean", tutu="median", tata="quartile")
print("-----")
ft_statistics("a", "b", toto="mean", tutu="std")
if __name__ == "__main__":
main()