Repository navigation
fix(maths): correct binomial_coefficient when n is 0 and r > 0 #15685
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,8 +12,10 @@ def binomial_coefficient(n: int, r: int) -> int: | |
| 252 | ||
| >>> binomial_coefficient(10, 0) | ||
| 1 | ||
| >>> binomial_coefficient(0, 10) | ||
| >>> binomial_coefficient(0, 0) | ||
| 1 | ||
| >>> binomial_coefficient(0, 10) | ||
| 0 | ||
| >>> binomial_coefficient(10, 10) | ||
| 1 | ||
| >>> binomial_coefficient(5, 2) | ||
|
|
@@ -41,8 +43,10 @@ def binomial_coefficient(n: int, r: int) -> int: | |
| """ | ||
| 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. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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. |
||
| return 1 | ||
| if r > n: | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 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. |
||
| return 0 | ||
| c = [0 for i in range(r + 1)] | ||
| # nc0 = 1 | ||
| c[0] = 1 | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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?