The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
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 # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb >>> comb(10,3) 120
Related Posts:
- Is there a math nCr function in python? [duplicate]
- How to send an email with Python?
- numpy max vs amax vs maximum
- What do these operators mean (** , ^ , %, //)? [closed]
- What do these operators mean (** , ^ , %, //)? [closed]
- How do I define a function with optional arguments?
- Basic explanation of python functions
- What is the naming convention in Python for variable and function names?
- syntaxerror: “unexpected character after line continuation character in python” math
- TypeError: ‘float’ object is not callable
- Error: all the input array dimensions except for the concatenation axis must match exactly
- How do order of operations go on Python?
- Call a function from another file?
- What does numpy.gradient do?
- Python Calling Function from Another File
- Python: OverflowError: math range error
- How can I use numpy.correlate to do autocorrelation?
- How can I convert radians to degrees with Python?
- What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?
- IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler
- Infinite integer in Python
- Apply function to each element of a list
- Python return list from function
- Overflow / math range error for log or exp
- How do I find the distance between two points?
- How can I check for NaN values?
- Python – how to use the constant e^
- log2 in python math module
- What is the difference between ‘/’ and ‘//’ when used for division?
- How can I check for NaN values?
- How to stop a function
- How can I check if two segments intersect?
- Repeating a function in Python
- python3 TypeError: ‘function’ object is not iterable
- How to get a function name as a string?
- Python: Can a function return an array and a variable?
- Call Python function from JavaScript code
- function is not defined error in Python
- python math domain errors in math.log function
- How to fix ‘RuntimeWarning: divide by zero encountered in double_scalars’
- How do I compute derivative using Numpy?
- Adding +1 to a variable inside a function
- Write a program that asks the user to enter five test scores. Correspond it to a letter grade
- Function to determine if two numbers are nearly equal when rounded to n significant decimal digits
- Multiplication function with recursion in Python
- Run function from the command line
- ImportError: No module named pandas. Pandas installed pip
- How to Execute a Python Script in Notepad++?
- ValueError: operands could not be broadcast together with shapes (5,) (30,)
- appending list but error ‘NoneType’ object has no attribute ‘append’
- Using Python 3 in virtualenv
- “Series objects are mutable and cannot be hashed” error
- Putting a simple if-then-else statement on one line [duplicate]
- matplotlib savefig() plots different from show()
- Converting list to numpy array
- How do I parse a string to a float or int?
- ValueError: max() arg is an empty sequence
- How do I insert a JPEG image into a python Tkinter window?
- Use a.any() or a.all()
- What is the difference between Spyder and Jupyter?
- What is the maximum recursion depth in Python, and how to increase it?
- subprocess.check_output return code
- What’s the idiomatic syntax for prepending to a short python list?
- What is the difference between “is None” and “== None”
- How to round a number to significant figures in Python
- Why Python 3.6.1 throws AttributeError: module ‘enum’ has no attribute ‘IntFlag’?
- Creating 2D dictionary in Python
- Python: slicing a multi-dimensional array
- Python: pandas merge multiple dataframes
- Shuffle an array with python, randomize array item order with python
- How to count the NaN values in a column in pandas DataFrame
- How to install multiple python packages at once using pip
- Running Selenium with Headless Chrome Webdriver
- Errno 13 Permission denied Python
- ValueError: object too deep for desired array while using convolution
- How to convert string to binary?
- How to iterate through two lists in parallel?
- Make list of arrays in python
- In Python, what is `sys.maxsize`?
- Pyspark: Exception: Java gateway process exited before sending the driver its port number
- Converting from a string to boolean in Python?
- Import Error: No module named numpy Anaconda
- How to remove \n from a list element?
- What is the common header format of Python files?
- Is it possible to decompile a compiled .pyc file into a .py file?
- Writing string to a file on a new line every time
- Creating lowpass filter in SciPy – understanding methods and units
- Python 2: AttributeError: ‘list’ object has no attribute ‘strip’
- Get Confusion Matrix From a Keras Multiclass Model
- AttributeError: ‘list’ object has no attribute ‘lower’ gensim
- How do I disable “missing docstring” warnings at a file-level in Pylint?
- How to convert column with dtype as object to string in Pandas Dataframe
- When I use matplotlib in jupyter notebook,it always raise ” matplotlib is currently using a non-GUI backend” error?
- How does ajax work with python?
- RSA encryption and decryption in Python
- Counting array elements in Python
- IPython, “name ‘plt’ not defined”
- ‘pyuic5’ is not recognized as an internal or external command
- ValueError: multiclass format is not supported
- Filtering a NumPy Array