Combination in Python

 Basics of the post

1. The combination is a selection-based technique where the element is selected from a set. 

2. The main difference between the combination and permutation is that order in the combination process does matter but order in permutation does matter.

3. The basic formula of combination has been given below. 'n' represents the total number of elements and 'r' represent the number of choosing elements in a set.

Read Similar Post: Permutation in Python

Step to solve Combination

The solution step is as same as permutation. The difference between the permutation and combination formula is little. Here we will use the permutation formula, as we know:

Combination = 1/r! * Permutation

    = 1/r! * n!/(n-r)!

    = n!/r!(n-r)!

1. First of all, two input values for 'n' and 'r' will be taken from the user input.

n=int(input())
r=int(input())

2. The factorial and permutation functions will same as the permutation process.

def factorial(n):
if (n>=1):
return n*factorial(n-1)
else:
return 1

def permutaion(n, r):
return factorial(n) / factorial(n-r)

3. We will create a combination function to calculate the combination of a set just like the formula. As n!/(n-r)! already implemented, we will multiply it with 1/r! for the combination process.

def combination(n, r):
return permutaion(n, r) / factorial(r)

4. At last, we will call the combination function which receives 'n' and 'r' parameters. 

result = int(combination(n,r))
print(result)

Now the final code will be like below, 

Combination in Python

n=int(input())
r=int(input())

def factorial(n):
if (n>=1):
return n*factorial(n-1)
else:
return 1

def combination(n, r):
return permutaion(n, r) / factorial(r)

def permutaion(n, r):
return factorial(n) / factorial(n-r)

result = int(combination(n,r))
print(result)

Sample Input:

100  /* n=100 */

10  /* r=10 */

Sample Output:

17310309456440

Post a Comment

Previous Post Next Post