8000 Misc cleanups and wording improvements for the itertools docs by rhettinger · Pull Request #119626 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

Misc cleanups and wording improvements for the itertools docs #119626

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 16 commits into from
May 27, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Tighten the wording for combinations_with_replacement().
  • Loading branch information
rhettinger committed May 25, 2024
commit 269b5062a20e68ace37ee7a86f9d23c9b1c5e8df
22 changes: 7 additions & 15 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -271,12 +271,17 @@ loops that truncate the stream.
Return *r* length subsequences of elements from the input *iterable*
allowing individual elements to be repeated more than once.

The output is a subsequence of :func:`product` that keeps only entries
that are subsequences (with possible repeated elements) of the
*iterable*. The number of subsequence returned is ``(n + r - 1)! / r! /
(n - 1)!`` when ``n > 0``.

The combination tuples are emitted in lexicographic order according to
the order of the input *iterable*. So, if the input *iterable* is sorted,
the order of the input *iterable*. if the input *iterable* is sorted,
the output tuples will be produced in sorted order.

Elements are treated as unique based on their position, not on their
value. So, if the input elements are unique, the generated combinations
value. If the input elements are unique, the generated combinations
will also be unique.

Roughly equivalent to::
Expand All @@ -298,19 +303,6 @@ loops that truncate the stream.
indices[i:] = [indices[i] + 1] * (r - i)
yield tuple(pool[i] for i in indices)

The code for :func:`combinations_with_replacement` can be also expressed as
a subsequence of :func:`product` after filtering entries where the elements
are not in sorted order (according to their position in the input pool)::

def combinations_with_replacement(iterable, r):
pool = tuple(iterable)
n = len(pool)
for indices in product(range(n), repeat=r):
if sorted(indices) == list(indices):
yield tuple(pool[i] for i in indices)

The number of items returned is ``(n+r-1)! / r! / (n-1)!`` when ``n > 0``.

.. versionadded:: 3.1


Expand Down
0