Skip to content

Commit 5fe505e

Browse files
committed
powerset: improve docstring
1 parent cae7994 commit 5fe505e

File tree

1 file changed

+14
-6
lines changed

1 file changed

+14
-6
lines changed

unpythonic/it.py

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -841,28 +841,36 @@ def powerset(iterable):
841841
# --> ((0,), (1,), (0, 1), (2,), (0, 2), (1, 2), (0, 1, 2))
842842
843843
# all divisors of 36 = 2 * 2 * 3 * 3
844-
tuple(sorted(prod(x) for x in uniqify(powerset([2, 2, 3, 3]))))
844+
tuple(sorted(prod(xs) for xs in uniqify(powerset([2, 2, 3, 3]))))
845845
# --> (2, 3, 4, 6, 9, 12, 18, 36)
846846
847847
If you want to try that for other positive integers, SymPy can perform
848848
the factorization::
849849
850850
import sympy as sy
851-
[k for k, v in sy.factorint(36).items() for _ in range(v)]
851+
[factor for factor, multiplicity in sy.factorint(36).items()
852+
for _ in range(multiplicity)]
852853
# --> [2, 2, 3, 3]
853854
855+
**NOTE**: The itertools recipe implementation is shorter than ours, and
856+
likely has better performance, but it assumes finite input; **we do not**.
857+
The `more-itertools` library packages that recipe, so the same limitation
858+
applies there, too. See:
859+
https://docs.python.org/3/library/itertools.html
860+
https://pypi.org/project/more-itertools/
861+
854862
**CAUTION**:
855863
856864
The size of the powerset of an iterable of length `n` is `2**n - 1`::
857865
858866
[len(list(powerset(range(k)))) for k in range(10)]
859867
# --> [0, 1, 3, 7, 15, 31, 63, 127, 255, 511]
860868
861-
(proof by induction) and furthermore the total item count in the subsets
869+
(proof by induction) and furthermore, the total item count in the subsets
862870
also grows quickly::
863871
864872
from collections import Counter
865-
def length_distribution(k):
873+
def length_distribution(k): # count of subsets of each length
866874
return Counter(sorted(len(x) for x in powerset(range(k))))
867875
def total_num_items(ld):
868876
return sum(length * count for length, count in ld.items())
@@ -883,8 +891,8 @@ def total_num_items(ld):
883891
total_num_items(d)
884892
# --> 5120
885893
886-
this becomes intractable quite quickly as the length of the input iterable
887-
grows.
894+
Hence, building all of the power set becomes intractable quite quickly as
895+
the length of the input iterable increases.
888896
"""
889897
it = iter(iterable)
890898
bag = []

0 commit comments

Comments
 (0)