Python 中是否有数学 nCr 函数?[重复]
- 2025-02-20 09:25:00
- admin 原创
- 28
问题描述:
math
Python库中是否包含如下所示的内置 nCr(n 选择 r)函数?
我知道计算是可以编程的,但我想在执行之前先检查一下它是否是内置的。
解决方案 1:
在 Python 3.8 + 上,使用math.comb
:
>>> from math import comb
>>> comb(10, 3)
120
对于旧版本的 Python,您可以使用以下程序:
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
解决方案 2:
想要迭代吗?使用itertools.combinations
。常见用法:
>>> import itertools
>>> itertools.combinations('abcd', 2)
<itertools.combinations object at 0x104e9f010>
>>> list(itertools.combinations('abcd', 2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd', 2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
如果您只需要计算公式,math.factorial
可以使用,但对于较大的组合来说速度并不快,但请参阅math.comb
下面的 Python 3.8+ 中可用的优化计算:
import math
def ncr(n, r):
f = math.factorial
return f(n) // f(r) // f(n-r)
print(ncr(4, 2)) # Output: 6
从 Python 3.8 开始,math.comb
可以使用并且速度更快:
>>> import math
>>> math.comb(4,2)
6
相关推荐
热门文章
项目管理软件有哪些?
- 2024年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)
热门标签
云禅道AD