← 中文资源

简体中文版本

math.comb 与 perm 数组合与排列

math.comb 数无序选取、math.perm 数有序排列,都是精确整数;k 大于 n 时 comb 返回 0 不报错,负数抛 ValueError;二项式求和恰等于 2 的 n 次方。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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 integer

实现说明

顶层就这几处状态:row。

使用要点

  • 演示输出是带标签的(comb(5, 2) =、comb(3, 5) =、sum C(n,k) =),每个操作都会留下自己的一行标注。

常见问题

运行之前需要装什么吗?

不需要——用到的每个 API 都随语言运行时自带,无需安装。 全部导入都来自标准库:math。 文件用顶层绑定保存自己的状态:row。

核心语句

except ValueError as exc:
    print("comb(3, -1)->", exc)

代码示例

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)