Skip to content
Open
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
74 changes: 74 additions & 0 deletions maths/ncr_combinations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""
Generalized nCr (combinations) calculator for real numbers n and integer r.
Wikipedia URL: https://en.wikipedia.org/wiki/Binomial_coefficient
"""

from math import factorial as math_factorial


def nCr(n: float, r: int) -> float:

Check failure on line 9 in maths/ncr_combinations.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N802)

maths/ncr_combinations.py:9:5: N802 Function name `nCr` should be lowercase
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Variable and function names should follow the snake_case naming convention. Please update the following name accordingly: nCr

Please provide descriptive name for the parameter: n

Please provide descriptive name for the parameter: r

"""
Compute the number of combinations (n choose r) for real n and integer r
using the formula:

nCr = n * (n-1) * (n-2) * ... * (n-r+1) / r!

Parameters
----------
n : float
Total number of items. Can be any real number.
r : int
Number of items to choose. Must be a non-negative integer.

Returns
-------
float
The number of combinations.

Raises
------
ValueError
If r is not an integer or r < 0

Examples
--------
>>> nCr(5, 2)
10.0
>>> nCr(5.5, 2)
12.375
>>> nCr(10, 0)
1.0
>>> nCr(0, 0)
1.0
>>> nCr(5, -1)
Traceback (most recent call last):
...
ValueError: r must be a non-negative integer
>>> nCr(5, 2.5)
Traceback (most recent call last):
...
ValueError: r must be a non-negative integer
"""
if not isinstance(r, int) or r < 0:
raise ValueError("r must be a non-negative integer")

if r == 0:
return 1.0

numerator = 1.0
for i in range(r):
numerator *= n - i

denominator = math_factorial(r)
return numerator / denominator


if __name__ == "__main__":
import doctest

doctest.testmod()

# Example usage
n = float(input("Enter n (real number): ").strip() or 0)
r = int(input("Enter r (integer): ").strip() or 0)
print(f"nCr({n}, {r}) = {nCr(n, r)}")
Loading