python - matplotlib文字 - plt set_title
python中有數學nCr函數嗎? (2)
我期待看看如果使用Python中的數學庫構建的是nCr(n Choose r)函數:
我明白,這可以編程,但我認為我會檢查之前,它是否已經內置。
https://ffff65535.com
以下程序以有效的方式計算nCr
(與計算階乘等相比)
import operator as op
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, xrange(n, n-r, -1), 1)
denom = reduce(op.mul, xrange(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(nr)
產量
6