
Get the number of permutations in Python: Calculate nPk (the number of ways to choose and order items)
The perm()
in math
module returns the number of patterns to choose k objects from n objects and order them, that is nPk.
math.perm(n, k=None)
The method is available from Python 3.8. The first argument is the number of total items and the second is the number of items you choose and order.
Example
Here is the examples of choosing 0 to 5 items from 5 items and ordering.
import math
p0 = math.perm(5, 0)
p1 = math.perm(5, 1)
p2 = math.perm(5, 2)
p3 = math.perm(5, 3)
p4 = math.perm(5, 4)
p5 = math.perm(5, 5)
print(p0, p1, p2, p3, p4, p5)
# 1 5 20 60 120 120
Choosing 2 items from 5 items with order has 20 ways.
perm(5, 2) = 5P2 = 5 × 4 = 20
In case k is not specified
p = math.perm(5)
print(p) # 120
The math.perm(5)
and math.perm(5, 5)
are equivalent and both are equal to 5! = 120.
Comments
Powered by Markdown