X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=list_utils.py;h=8f92be30c45fba8531654895f7a03da29b18dae7;hb=581d759e55faf532fcf3c89d59eae929ede24dd7;hp=5c70df3476c6dbafe3c252788e88ee6b16c5c301;hpb=532df2c5b57c7517dfb3dddd8c1358fbadf8baf3;p=python_utils.git diff --git a/list_utils.py b/list_utils.py index 5c70df3..8f92be3 100644 --- a/list_utils.py +++ b/list_utils.py @@ -6,7 +6,7 @@ import random from collections import Counter -from itertools import islice +from itertools import chain, combinations, islice from typing import Any, Iterator, List, MutableSequence, Sequence, Tuple @@ -259,7 +259,7 @@ def scramble(seq: MutableSequence[Any]) -> MutableSequence[Any]: return shuffle(seq) -def binary_search(lst: Sequence[Any], target: Any, *, sanity_check=False) -> Tuple[bool, int]: +def binary_search(lst: Sequence[Any], target: Any) -> Tuple[bool, int]: """Performs a binary search on lst (which must already be sorted). Returns a Tuple composed of a bool which indicates whether the target was found and an int which indicates the index closest to @@ -285,7 +285,7 @@ def binary_search(lst: Sequence[Any], target: Any, *, sanity_check=False) -> Tup AssertionError """ - if sanity_check: + if __debug__: last = None for x in lst: if last is not None: @@ -307,6 +307,23 @@ def _binary_search(lst: Sequence[Any], target: Any, low: int, high: int) -> Tupl return (False, low) +def powerset(lst: Sequence[Any]) -> Iterator[Sequence[Any]]: + """Returns the powerset of the items in the input sequence. + + >>> for x in powerset([1, 2, 3]): + ... print(x) + () + (1,) + (2,) + (3,) + (1, 2) + (1, 3) + (2, 3) + (1, 2, 3) + """ + return chain.from_iterable(combinations(lst, r) for r in range(len(lst) + 1)) + + if __name__ == '__main__': import doctest