math.comb And perm Count Combinations
math.comb counts unordered picks, math.perm counts ordered ones, k greater than n yields 0 instead of an error, and negative inputs raise ValueError.
Code
import math
# math.comb(n, k) 数组合数,math.perm(n, k) 数排列数:都是精确整数
print("comb(5, 2) =", math.comb(5, 2), "| perm(5, 2) =", math.perm(5, 2))
print("perm(5) =", math.perm(5), "= 5!")
# k > n 时没有组合可选:comb 返回 0 而不是报错
print("comb(3, 5) =", math.comb(3, 5))
# 帕斯卡三角一行:相邻组合数相加
row = [math.comb(4, k) for k in range(5)]
print("row n=4 :", row)
# 二项式定理的对账恒等式:C(n,0)+...+C(n,n) = 2**n
n = 10
print("sum C(n,k) =", sum(math.comb(n, k) for k in range(n + 1)), "== 2**n =", 2**n)
# 取样场景:从 52 张牌抽 5 张的组合数与有序发牌数
print("poker hands:", math.comb(52, 5), "| ordered :", math.perm(52, 5))
# 负数直接抛 ValueError
try:
math.comb(3, -1)
except ValueError as exc:
print("comb(3, -1)->", exc)Output
Captured from a sandboxed run of this snippet in the build pipeline.
comb(5, 2) = 10 | perm(5, 2) = 20
perm(5) = 120 = 5!
comb(3, 5) = 0
row n=4 : [1, 4, 6, 4, 1]
sum C(n,k) = 1024 == 2**n = 1024
poker hands: 2598960 | ordered : 311875200
comb(3, -1)-> k must be a non-negative integerInside the snippet
Everything operates on top-level bindings: row.
Caveats
- Entirely standard-library — copy it in and it runs.
Putting it to use
Look for the comb(5, 2) =, perm(5) =, comb(3, 5) = prefixes when the file runs; they tie each line to its step.
Core lines
except ValueError as exc:
print("comb(3, -1)->", exc)
Interactive Tools for This Topic
GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Vector Similarity CalculatorCompute Cosine Similarity, Dot Product, Euclidean L2, Manhattan L1, and Chebyshev distances between numeric vectors with dimension checks.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `math`. Its state lives in module-level bindings: `row`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.