YouTip LogoYouTip

Ref Math Perm

## Python math.perm() Method The `math.perm()` method is a built-in function in Python's standard `math` module. It is used to calculate the number of permutations: the total number of ways to choose $k$ items from $n$ items without repetition and with order. ### Introduction In mathematics, a permutation is the arrangement of all or part of a set of objects in a specific order. The `math.perm(n, k)` method returns the number of ordered arrangements of $k$ items selected from a pool of $n$ unique items. * **With $k$ specified:** The result is calculated as: $$P(n, k) = \frac{n!}{(n-k)!}$$ * **Without $k$ specified:** If $k$ is omitted, the method returns the total number of permutations of $n$ items, which is equivalent to $n!$ (factorial of $n$). For example, `math.perm(7)` returns `5040`. **Python Version:** Added in Python 3.8. --- ### Syntax ```python import math math.perm(n, k=None) ``` #### Parameters | Parameter | Type | Description | | :--- | :--- | :--- | | **`n`** | `int` | **Required.** The total number of items in the pool. Must be a non-negative integer. | | **`k`** | `int` | **Optional.** The number of items to choose. If omitted, defaults to `None` (which calculates $n!$). | #### Return Value * Returns an **`int`** representing the total number of ordered ways to choose $k$ items from $n$ items. --- ### Exceptions and Edge Cases * **`TypeError`**: Raised if either `n` or `k` is not an integer. * **`ValueError`**: Raised if either `n` or `k` is a negative number. * **$k > n$**: If $k$ is greater than $n$, the method returns `0` (since you cannot choose more items than are available without repetition). --- ### Code Examples #### Example 1: Basic Permutation ($P(n, k)$) Calculate the number of ways to choose and arrange 5 items from a pool of 7 items. ```python import math # Initialize n and k n = 7 k = 5 # Calculate permutations result = math.perm(n, k) print(f"Permutations of choosing {k} from {n}: {result}") ``` **Output:** ```text Permutations of choosing 5 from 7: 2520 ``` --- #### Example 2: Permutation Without the $k$ Parameter If you do not provide the $k$ parameter, the method calculates the full factorial of $n$ ($n!$). ```python import math # Calculate permutations of 7 items (7!) result = math.perm(7) print(f"Permutations of 7 items: {result}") ``` **Output:** ```text Permutations of 7 items: 5040 ``` --- #### Example 3: Handling Edge Cases ($k > n$) If $k$ is greater than $n$, the method returns `0`. ```python import math # Attempting to choose 5 items from a pool of 3 result = math.perm(3, 5) print(f"Permutations of choosing 5 from 3: {result}") ``` **Output:** ```text Permutations of choosing 5 from 3: 0 ``` --- ### Summary * Use `math.perm(n, k)` when the **order of selection matters** (e.g., arranging people in chairs, forming passwords). * If the order of selection does **not** matter, use `math.comb(n, k)` (combinations) instead.
← Ref Math RemainderRef Math Hypot β†’