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
kis optional. If we do not provide it, this method will returnn!. For example,math.perm(4)returns4!, i.e.,24.
Return value
The function returns an integer that corresponds to the result from the following formula:
Code
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))
Explanation
-
In line 2, we imported the
mathmodule 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:
In this way, we can use the math.perm() function in Python to compute the permutation of any two given numbers.