How to use the math.perm() function in Python

The math.perm() function in Python is used to return the number of permutations of k items from a group of n items, i.e., it helps us figure out the number of ways in which we can choose k items from n items with order and without repetition.

The math module in Python contains a number of mathematical operations that can be performed very easily. Amongst some of the most important functions in this module, the perm() function has its own importance.

This function was recently introduced Python 3.8. You can use the math.perm() function in Python versions 3.8 and above.

Syntax

math.perm(n, k)

Parameters

  • n: Total number of items. Needs to be a non-negative integer.
  • p: Number of objects to be selected. Needs to be a non-negative integer.

The parameter k is optional. If we do not provide it, this method will return n!. For example, math.perm(4) returns 4!, i.e., 24.

Return value

The function returns an integer that corresponds to the result from the following formula:

math.perm(n,k)=nPk=n!(nk)!math.perm(n, k) = nP_{k} = \frac{n!}{(n-k)!}

Code

Let us look at the code snippet below.

# Import math Library
import math
# Initialize n
n = 7
# Initialize k
k = 5
# Print the number of ways to choose k items from n items
print (math.perm(n, k))

Explanation

  • In line 2, we imported the math module in Python.

  • In line 5, we initialize the number of items to choose from (n).

  • In line 8, we initialize the number of items to choose (k).

  • In line 11, we use the math.perm() function and compute the requisite.

Output

The output is:

7P5=7!(75)!=7!6!5!4!3!=25207P_{5} = \frac{7!}{(7-5)!} = 7!*6!*5!*4!*3! = 2520

In this way, we can use the math.perm() function in Python to compute the permutation of any two given numbers.

Free Resources