2024-05-15 23:12:29 发布
网友
Possible Duplicates:Statistics: combinations in Pythoncounting combinations and permutations efficientlyProject euler problem in python (problem 53)
我想看看python中的数学库是否内置了nCr(n Choose r)函数:
我知道这是可以编程的,但我想我会先检查一下它是否已经内置了。
以下程序以有效的方式计算nCr(与计算阶乘等相比)
nCr
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
你想要迭代吗?itertools.combinations。常用用法:
>>> import itertools >>> itertools.combinations('abcd',2) <itertools.combinations object at 0x01348F30> >>> 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:
import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(n-r) if __name__ == '__main__': print nCr(4,2)
在Python 3中,使用整数除法//而不是/来避免溢出:
//
/
return f(n) // f(r) // f(n-r)
6
以下程序以有效的方式计算
nCr
(与计算阶乘等相比)你想要迭代吗?itertools.combinations。常用用法:
如果只需要计算公式,请使用math.factorial:
在Python 3中,使用整数除法
//
而不是/
来避免溢出:return f(n) // f(r) // f(n-r)
输出
相关问题 更多 >
编程相关推荐