Skip to content

Commit

Permalink
Improve the fidelity of the product() rough equivalent
Browse files Browse the repository at this point in the history
  • Loading branch information
rhettinger committed Sep 9, 2024
1 parent 903bbfc commit 2ffdaa1
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
2 changes: 2 additions & 0 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,8 @@ loops that truncate the stream.
# product('ABCD', 'xy') → Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) → 000 001 010 011 100 101 110 111

if repeat < 0:
raise ValueError('repeat argument cannot be negative')
pools = [tuple(pool) for pool in iterables] * repeat

result = [[]]
Expand Down
8 changes: 6 additions & 2 deletions Lib/test/test_itertools.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,12 +992,16 @@ def product1(*args, **kwds):
else:
return

def product2(*args, **kwds):
def product2(*iterables, repeat=1):
'Pure python version used in docs'
pools = list(map(tuple, args)) * kwds.get('repeat', 1)
if repeat < 0:
raise ValueError('repeat argument cannot be negative')
pools = [tuple(pool) for pool in iterables] * repeat

result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]

for prod in result:
yield tuple(prod)

Expand Down

0 comments on commit 2ffdaa1

Please sign in to comment.