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.
math.perm(n, k)
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 returnn!
. For example,math.perm(4)
returns4!
, i.e.,24
.
The function returns an integer that corresponds to the result from the following formula:
Let us look at the code snippet below.
# Import math Libraryimport math# Initialize nn = 7# Initialize kk = 5# Print the number of ways to choose k items from n itemsprint (math.perm(n, k))
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.
The output is:
In this way, we can use the math.perm()
function in Python to compute the permutation of any two given numbers.