Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - Functions

Function to return nCr (Combinations) - Python Program

Example 1 :

import math def nCr(n, r): """Return combinations.""" return math.comb(n, r) print(nCr(5, 2))

Output

 
OUTPUT  :
10 
 

Example 2 :

import math def calculate_nCr(n, r): """ Calculates the number of combinations (nCr) using the formula: n! / (r! * (n-r)!). Args: n (int): The total number of items available. r (int): The number of items to choose. Returns: int: The number of combinations, or 0 if r > n. """ if r < 0 or r > n: return 0 # Invalid input for combinations # Using math.comb for efficiency in Python 3.8+ # For older Python versions, manual factorial calculation would be needed # return math.factorial(n) // (math.factorial(r) * math.factorial(n - r)) return math.comb(n, r) # Example Usage: n_val = 5 r_val = 2 result = calculate_nCr(n_val, r_val) print(f"The number of combinations for C({n_val}, {r_val}) is: {result}") n_val_2 = 10 r_val_2 = 3 result_2 = calculate_nCr(n_val_2, r_val_2) print(f"The number of combinations for C({n_val_2}, {r_val_2}) is: {result_2}") n_val_3 = 4 r_val_3 = 5 result_3 = calculate_nCr(n_val_3, r_val_3) print(f"The number of combinations for C({n_val_3}, {r_val_3}) is: {result_3}")

Output

 
OUTPUT  :
The number of combinations for C(5, 2) is: 10
The number of combinations for C(10, 3) is: 120
The number of combinations for C(4, 5) is: 0