Python/maths/combinations.py
SubhranShu2332 e7a59bfff5
In place of calculating the factorial several times we can run a loop k times to calculate the combination (#10051)
* In place of calculating the factorial several times we can run a loop k times to calculate the combination 

for example:
5 C 3 = 5! / (3! * (5-3)! )
= (5*4*3*2*1)/[(3*2*1)*(2*1)]
=(5*4*3)/(3*2*1)
so running a loop k times will reduce the time complexity to O(k)

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update maths/combinations.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Tianyi Zheng <tianyizheng02@gmail.com>
2023-10-08 15:17:02 -04:00

61 lines
1.4 KiB
Python

"""
https://en.wikipedia.org/wiki/Combination
"""
def combinations(n: int, k: int) -> int:
"""
Returns the number of different combinations of k length which can
be made from n values, where n >= k.
Examples:
>>> combinations(10,5)
252
>>> combinations(6,3)
20
>>> combinations(20,5)
15504
>>> combinations(52, 5)
2598960
>>> combinations(0, 0)
1
>>> combinations(-4, -5)
...
Traceback (most recent call last):
ValueError: Please enter positive integers for n and k where n >= k
"""
# If either of the conditions are true, the function is being asked
# to calculate a factorial of a negative number, which is not possible
if n < k or k < 0:
raise ValueError("Please enter positive integers for n and k where n >= k")
res = 1
for i in range(k):
res *= n - i
res //= i + 1
return res
if __name__ == "__main__":
print(
"The number of five-card hands possible from a standard",
f"fifty-two card deck is: {combinations(52, 5)}\n",
)
print(
"If a class of 40 students must be arranged into groups of",
f"4 for group projects, there are {combinations(40, 4)} ways",
"to arrange them.\n",
)
print(
"If 10 teams are competing in a Formula One race, there",
f"are {combinations(10, 3)} ways that first, second and",
"third place can be awarded.",
)