Skip to content

Commit 4f457c5

Browse files
committed
Create ncr_combinations.py
1 parent e2a78d4 commit 4f457c5

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

maths/ncr_combinations.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
"""
2+
Generalized nCr (combinations) calculator for real numbers n and integer r.
3+
Wikipedia URL: https://en.wikipedia.org/wiki/Binomial_coefficient
4+
"""
5+
6+
from math import factorial as math_factorial
7+
8+
9+
def nCr(n: float, r: int) -> float:
10+
"""
11+
Compute the number of combinations (n choose r) for real n and integer r
12+
using the formula:
13+
14+
nCr = n * (n-1) * (n-2) * ... * (n-r+1) / r!
15+
16+
Parameters
17+
----------
18+
n : float
19+
Total number of items. Can be any real number.
20+
r : int
21+
Number of items to choose. Must be a non-negative integer.
22+
23+
Returns
24+
-------
25+
float
26+
The number of combinations.
27+
28+
Raises
29+
------
30+
ValueError
31+
If r is not an integer or r < 0
32+
33+
Examples
34+
--------
35+
>>> nCr(5, 2)
36+
10.0
37+
>>> nCr(5.5, 2)
38+
12.375
39+
>>> nCr(10, 0)
40+
1.0
41+
>>> nCr(0, 0)
42+
1.0
43+
>>> nCr(5, -1)
44+
Traceback (most recent call last):
45+
...
46+
ValueError: r must be a non-negative integer
47+
>>> nCr(5, 2.5)
48+
Traceback (most recent call last):
49+
...
50+
ValueError: r must be a non-negative integer
51+
"""
52+
if not isinstance(r, int) or r < 0:
53+
raise ValueError("r must be a non-negative integer")
54+
55+
if r == 0:
56+
return 1.0
57+
58+
numerator = 1.0
59+
for i in range(r):
60+
numerator *= n - i
61+
62+
denominator = math_factorial(r)
63+
return numerator / denominator
64+
65+
66+
if __name__ == "__main__":
67+
import doctest
68+
69+
doctest.testmod()
70+
71+
# Example usage
72+
n = float(input("Enter n (real number): ").strip() or 0)
73+
r = int(input("Enter r (integer): ").strip() or 0)
74+
print(f"nCr({n}, {r}) = {nCr(n, r)}")

0 commit comments

Comments
 (0)