擅长:python、mysql、java
<p>你想要迭代吗?<a href="http://docs.python.org/library/itertools.html?highlight=itertools.combinations#itertools.combinations" rel="noreferrer">itertools.combinations</a>。常用用法:</p>
<pre><code>>>> 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']
</code></pre>
<p>如果只需要计算公式,请使用<a href="http://docs.python.org/library/math.html?highlight=math.factorial#math.factorial" rel="noreferrer">math.factorial</a>:</p>
<pre><code>import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
</code></pre>
<p>在Python 3中,使用整数除法<code>//</code>而不是<code>/</code>来避免溢出:</p>
<p><code>return f(n) // f(r) // f(n-r)</code></p>
<h3>输出</h3>
<pre><code>6
</code></pre>