Repository navigation
fix(maths): correct binomial_coefficient when n is 0 and r > 0 - #15685
saiyam-jain-dev wants to merge 1 commit into
Conversation
Multiple Pull Request Detected@saiyam-jain-dev, we are extremely excited that you want to submit multiple algorithms in this repository but we have a limit on how many pull request a user can keep open at a time. This is to make sure all maintainers and users focus on a limited number of pull requests at a time to maintain the quality of the code. This pull request is being closed as the user already has an open pull request. Please focus on your previous pull request before opening another one. Thank you for your cooperation. User opened pull requests (including this one): #15685, #15645, #15644, #15643, #15642 |
| if 0 in (n, r): | ||
| if r == 0: | ||
| return 1 | ||
| if r > n: |
There was a problem hiding this comment.
This early return is correct and also useful beyond the n == 0 case: without it, something like binomial_coefficient(5, 10**9) would first allocate c = [0] * (r + 1), a huge list, before returning 0. Could you add a doctest for r > n with n > 0 (e.g. binomial_coefficient(3, 5) -> 0)? The current doctests only cover r > n for n = 0.
| >>> binomial_coefficient(0, 0) | ||
| 1 | ||
| >>> binomial_coefficient(0, 10) | ||
| 0 |
There was a problem hiding this comment.
Good that the doctest now expects 0, since C(0, 10) = 0. The old expected value of 1 was wrong because 0 in (n, r) matched n == 0. Could you also add (0, 1) -> 0, which is the smallest case that hit the old bug?
| if n < 0 or r < 0: | ||
| raise ValueError("n and r must be non-negative integers") | ||
| if 0 in (n, r): | ||
| if r == 0: |
There was a problem hiding this comment.
Nice: this fixes the n = 0, r > 0 case that the old 0 in (n, r) check treated as 1, and C(0, 0) = 1 is still covered by the new (0, 0) doctest. Please add a short sentence in the docstring or PR description saying the function returns 0 when r > n, so readers see that behaviour is intended.
Describe your change
Checklist
Summary
In
maths/binomial_coefficient.py,binomial_coefficient(n, r)used:Because of this check,
binomial_coefficient(0, r)returned1for anyr > 0(such asbinomial_coefficient(0, 10) == 1).Mathematically, the binomial coefficient$\binom{n}{r}$ represents the number of ways to choose $r$ elements from a set of $n$ elements. When $r > n \ge 0$ , $\binom{n}{r} = 0$ . For all other cases where $r > n$ (e.g. $n = 0, r > 0$ case returned
binomial_coefficient(5, 6)orbinomial_coefficient(3, 5)), the function correctly returned0. Only the1incorrectly due to0 in (n, r).Changes
if 0 in (n, r): return 1with standard boundary handling:math.comb.Testing
math.comb(n, r)for allpytest maths/binomial_coefficient.py --doctest-modulespassed.ruff check maths/binomial_coefficient.pypassed.ruff format --check maths/binomial_coefficient.pypassed.