-
-
Notifications
You must be signed in to change notification settings - Fork 50.5k
Expand file tree
/
Copy pathncr_combinations.py
More file actions
74 lines (59 loc) · 1.6 KB
/
ncr_combinations.py
File metadata and controls
74 lines (59 loc) · 1.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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:
"""
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)}")