Skip to content
Closed
Changes from all commits
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
8 changes: 6 additions & 2 deletions maths/binomial_coefficient.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Copy link
Copy Markdown

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?

>>> binomial_coefficient(10, 10)
1
>>> binomial_coefficient(5, 2)
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The 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
Expand Down
Loading