Skip to content

Commit

Permalink
add average or raise
Browse files Browse the repository at this point in the history
  • Loading branch information
thejaminator committed Oct 18, 2023
1 parent 12a9946 commit 6a9b8da
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions slist/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,21 +593,22 @@ def sum(
"""Returns 0 when the list is empty"""
return sum(self)

@overload
def average(self: Sequence[int]) -> Optional[float]:
...

@overload
def average(self: Sequence[float]) -> Optional[float]:
...

def average(
self: Sequence[Union[int, float, bool]],
) -> Optional[float]:
"""Returns None when the list is empty"""
this = typing.cast(Slist[Union[int, float, bool]], self)
return this.sum() / this.length if this.length > 0 else None

def average_or_raise(
self: Sequence[Union[int, float, bool]],
) -> float:
"""Returns None when the list is empty"""
this = typing.cast(Slist[Union[int, float, bool]], self)
if this.length == 0:
raise ValueError("Cannot get average of empty list")
return this.sum() / this.length

def standard_deviation(self: Slist[Union[int, float]]) -> Optional[float]:
"""Returns None when the list is empty"""
return statistics.stdev(self) if self.length > 0 else None
Expand Down

0 comments on commit 6a9b8da

Please sign in to comment.