liveBook · Manning

Combination with replacement

As explained in Statistics Every Programmer Needs

A combination with replacement is a selection in which order does not matter and selected items may be selected again.

A combination with replacement counts selections when an item may be chosen more than once and order does not matter. Choose this rule for a pizza that can have extra helpings of the same topping: pepperoni, pepperoni, and mushrooms is one combination regardless of selection order. section 2.2.3

For r selections from n distinct available items, the count is (n + r − 1)! / [r!(n − 1)!], or “n + r − 1 choose r.” Placeholder positions turn the repeatable-selection count into a combination count. In Python, compute it with `math.comb(n + r - 1, r)`. section 2.2.3

Three toppings from five ingredients

Set `n = 5` and `r = 3`. Then `math.comb(5 + 3 - 1, 3)` returns `35`. Without replacement, `math.comb(5, 3)` returns only `10`: repeated toppings account for the additional possibilities. section 2.2.3

Five cards, returning each card

If each selected card goes back into a 52-card deck and draw order does not matter, calculate `math.comb(52 + 5 - 1, 5)`, or `math.comb(56, 5)`. The result is `3,819,816` combinations. section 3.2.3

>>> combinations = math.comb(n + r - 1, r)
>>> print(f'Number of combinations with replacement: '
>>>       f'{combinations}')
Number of combinations with replacement: 35

The Python listing shows the direct `math.comb(n + r - 1, r)` calculation for five options and three selections. section 2.2.3

How Statistics Every Programmer Needs covers it

How deep it goes
Derives the counting formula from combinations without replacement using placeholders, then calculates it with factorials and `math.comb()`.
Examples
Works through three pizza toppings from five ingredients and five returned-card selections from a 52-card deck.
What it assumes
Builds on combinations without replacement and factorial notation while defining repeated selection and order irrelevance through a pizza example.
What you can do after
Apply it via Python's `math.comb()` to count unordered selections in which items can be selected again.
How it connects
Distinguishes combinations without replacement and permutations through the separate questions of repetition and selection order.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Statistics Every Programmer Needs. The section links point to the parts of the book it draws on.