Jam*_*rtz 155 python math function
我想看看在python中使用数学库内置的是nCr(n选择r)函数:
我知道这可以编程,但我想我会先查看它是否已经内置.
Mar*_*nen 167
你想要迭代吗?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']
Run Code Online (Sandbox Code Playgroud)
如果您只需要计算公式,请使用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)
Run Code Online (Sandbox Code Playgroud)
在Python 3中,使用整数除法//
而不是/
为了避免溢出:
return f(n) // f(r) // f(n-r)
6
Run Code Online (Sandbox Code Playgroud)
dhe*_*aur 154
以下程序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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
209033 次 |
最近记录: |