Python math.perm() - Permutations


Python math.perm()

math.perm(n, k) function returns the number of ways to choose k items from n items without repetition and with order.

perm(n, k) = n! / (n - k)!

Syntax

The syntax to call perm() function is

math.perm(n, k=None)

where

ParameterRequiredDescription
nYesAn integer value.
kNoAn integer value. Default value is None.

If k is not given, perm(n) returns n!.

If either n or k is not an integer, then perm() raises TypeError.

If either n or k is negative, then perm() raises ValueError.

Examples

1. Permutations of picking 2 items out of 5

In the following program, we find the number of permutations of picking 2 items out of 5.

Python Program

import math

n = 5
k = 2
result = math.perm(n, k)
print('perm(n, k) :', result)

Output

perm(n, k) : 20

2. perm(n, k) when k is not given

If we do not pass any value for parameter k, then perm() returns all the possible permutations for given n.

Python Program

import math

n = 4
result = math.perm(n)
print('perm(n) :', result)

Output

perm(n) : 24

3. perm(n, k) when n is negative

If n is negative, then perm() throws ValueError.

Python Program

import math

n = -5
k = 2
result = math.perm(n, k)
print('perm(n, k) :', result)

Output

ValueError: n must be a non-negative integer

4. perm(n, k) when n is a float value

If n is a floating point number, then perm() throws TypeError.

Python Program

import math

n = 5.1
k = 2
result = math.perm(n, k)
print('perm(n, k) :', result)

Output

TypeError: 'float' object cannot be interpreted as an integer

Summary

In this Python Math tutorial, we learned the syntax of, and examples for math.perm() function.