#!/usr/bin/env python3
-# © Copyright 2021-2022, Scott Gasch
+# © Copyright 2021-2023, Scott Gasch
"""This module contains helper functions for dealing with Python lists."""
import random
from collections import Counter
from itertools import chain, combinations, islice
-from typing import Any, Iterator, List, MutableSequence, Sequence, Tuple
+from typing import (
+ Any,
+ Generator,
+ Iterator,
+ List,
+ MutableSequence,
+ Sequence,
+ Tuple,
+ TypeVar,
+)
def shard(lst: List[Any], size: int) -> Iterator[Any]:
return Counter(lst)
-def most_common(lst: List[Any], *, count=1) -> Any:
+def most_common(lst: List[Any], *, count: int = 1) -> Any:
"""
Return the N most common item in the list.
return remove_list_if_one_element([_[0] for _ in p.most_common()[0:count]])
-def least_common(lst: List[Any], *, count=1) -> Any:
+def least_common(lst: List[Any], *, count: int = 1) -> Any:
"""
Return the N least common item in the list.
return [list(_) for _ in transposed]
-def ngrams(lst: Sequence[Any], n: int):
+T = TypeVar('T')
+
+
+def ngrams(lst: Sequence[T], n: int) -> Generator[Sequence[T], T, None]:
"""
Return the ngrams in the sequence.
yield lst[i : i + n]
-def permute(seq: str):
+def permute(seq: str) -> Generator[str, str, None]:
"""
Returns all permutations of a sequence.
yield from _permute(seq, "")
-def _permute(seq: str, path: str):
+def _permute(seq: str, path: str) -> Generator[str, str, None]:
"""Internal helper to permute items recursively."""
seq_len = len(seq)
if seq_len == 0:
return chain.from_iterable(combinations(seq, r) for r in range(len(seq) + 1))
-if __name__ == '__main__':
+if __name__ == "__main__":
import doctest
doctest.testmod()