Skip to content

Commit

Permalink
Merge pull request #37 from PickwickSoft/feature/add-sum-operation-to…
Browse files Browse the repository at this point in the history
…-numerical-stream

Add `sum()` operation to numerical streams
  • Loading branch information
garlontas authored Jun 20, 2023
2 parents cdb941d + 4865d2c commit b27adff
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 0 deletions.
7 changes: 7 additions & 0 deletions pystreamapi/_streams/numeric/__numeric_base_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ def range(self) -> Union[float, int, None]:
self._trigger_exec()
return max(self._source) - min(self._source) if len(self._source) > 0 else None

@abstractmethod
def sum(self) -> Union[float, int, None]:
"""
Calculates the sum of all items of a numerical stream
:return: The sum, can be int or float
"""

def third_quartile(self) -> Union[float, int, None]:
"""
Calculates the third quartile of a numerical Stream
Expand Down
6 changes: 6 additions & 0 deletions pystreamapi/_streams/numeric/__parallel_numeric_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ def mean(self) -> Union[float, int, None]:
self._trigger_exec()
return self.__sum() / len(self._source) if len(self._source) > 0 else None

def sum(self) -> Union[float, int, None]:
"""Calculates the sum of values"""
self._trigger_exec()
_sum = self.__sum()
return 0 if _sum == [] else _sum

def __sum(self):
"""Parallel sum method"""
self._set_parallelizer_src()
Expand Down
5 changes: 5 additions & 0 deletions pystreamapi/_streams/numeric/__sequential_numeric_stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,8 @@ def mean(self) -> Union[float, int, None]:
"""Calculates mean of values"""
self._trigger_exec()
return sum(self._source) / len(self._source) if len(self._source) > 0 else None

def sum(self) -> Union[float, int, None]:
"""Calculates the sum of values"""
self._trigger_exec()
return sum(self._source)
8 changes: 8 additions & 0 deletions tests/test_numeric_stream_implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,11 @@ def test_mean_empty(self):
def test_mean_negative(self):
result = self.stream([-1, -2, -3, -4, -5]).mean()
self.assertEqual(result, -3)

def test_sum(self):
result = self.stream([1, 2, 3, 4, 5]).sum()
self.assertEqual(result, 15)

def test_sum_empty(self):
result = self.stream([]).sum()
self.assertEqual(result, 0)

0 comments on commit b27adff

Please sign in to comment.