nCr in Python.

{}_nC_r = \frac{n!}{(n-r)!r!}
In other words, it is a combination that takes out r out of n. I want to write this in Python. In such a case, use the higher-order function reduce.

import operator as op
def ncr(n,r):
    r = min(n-r,r)
    if r == 0:
        return 1
    num_over = reduce(op.mul, xrange(n, n - r, -1))
    num_under = reduce(op.mul, xrange(1,r + 1))
    return num_over // num_under

If you write with a lambda expression,

reduce(lambda x, y: x * y, xrange(n, n - r, -1))

Write like.

Recommended Posts

nCr in python
nCr in Python.
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Disassemble in Python
Reflection in Python
Constant in python
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python
Read DXF in python
Daily AtCoder # 53 in Python
Key input in Python
Use config.ini in Python
Daily AtCoder # 33 in Python
Solve ABC168D in Python
Logistic distribution in Python
LU decomposition in Python
One liner in Python
Simple gRPC in Python
Daily AtCoder # 24 in Python
Solve ABC167-D in Python