Skip to content

Commit 7db2d96

Browse files
committed
counted_groups -> dedup_counting
1 parent 4ed3c73 commit 7db2d96

File tree

1 file changed

+19
-20
lines changed

1 file changed

+19
-20
lines changed

typed_stream/streams.py

+19-20
Original file line numberDiff line numberDiff line change
@@ -546,26 +546,6 @@ def count(self) -> int:
546546
"""
547547
return self._finish(count(self._data), close_source=True)
548548

549-
def counted_groups(
550-
self: Stream[T], key: Callable[[T], object] | None = None
551-
) -> Stream[tuple[T, int]]:
552-
"""Group the stream by a key and count the items in the group.
553-
554-
>>> Stream("abba").counted_groups().starmap(print).for_each()
555-
a 1
556-
b 2
557-
a 1
558-
>>> Stream("aaabbbbc").counted_groups(ord).starmap(print).for_each()
559-
a 3
560-
b 4
561-
c 1
562-
"""
563-
564-
def _map(_: object, g: Iterator[T]) -> tuple[T, int]:
565-
return (next(g), 1 + count(g))
566-
567-
return Stream(itertools.starmap(_map, itertools.groupby(self, key)))
568-
569549
def dedup(self, *, key: None | Callable[[T], object] = None) -> Self:
570550
"""Remove consecutive equal values.
571551
@@ -595,6 +575,25 @@ def dedup(self, *, key: None | Callable[[T], object] = None) -> Self:
595575
)
596576
return self
597577

578+
def dedup_counting(self) -> Stream[tuple[T, int]]:
579+
"""Group the stream and count the items in the group.
580+
581+
>>> Stream("abba").dedup_counting().starmap(print).for_each()
582+
a 1
583+
b 2
584+
a 1
585+
>>> Stream("AaaaBBcccc").dedup_counting().starmap(print).for_each()
586+
A 1
587+
a 3
588+
B 2
589+
c 4
590+
"""
591+
592+
def _map(k: T, g: Iterator[T]) -> tuple[T, int]:
593+
return (k, count(g))
594+
595+
return Stream(itertools.starmap(_map, itertools.groupby(self)))
596+
598597
@override
599598
def distinct(self, *, use_set: bool = True) -> Self:
600599
"""Remove duplicate values.

0 commit comments

Comments
 (0)