
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Program to find nCr values for r in range 0 to n, in an efficient way in Python
Suppose we have to calculate nCr values many times. We can solve this very efficient way. If we store the lower values of nCr we can easily find higher values. So if we have n, we have to find list of nC0 to nCn. If answer is too large then return that modulo 10^9.
So, if the input is like n = 6, then the output will be [1, 6, 15, 20, 15, 6, 1].
To solve this, we will follow these steps −
- items := a list with single element 1
- for r in range 1 to n, do
- insert floor of (last element of items * (n-r+1) /r) at the end of items
- items[n-2] := items[n-2] mod 10^9 where n is size of items
- return items
Example
Let us see the following implementation to get better understanding −
def solve(n): items = [1] for r in range(1,n+1): items.append(items[-1]*(n-r+1)//r) items[-2] %= 10**9 return items n = 6 print(solve(n))
Input
6
Output
[1, 6, 15, 20, 15, 6, 1]
- Related Articles
- Program to find ex in an efficient way in Python
- Program to find out the efficient way to study in Python
- How to find the range for 95% of all values in an R vector?
- What is an efficient way to repeat a string to a certain length in Python?
- Program to count total number of set bits of all numbers in range 0 to n in Python
- Haskell Program To Perform nCr (r-combinations)
- How to find the n number of largest values in an R vector?
- How to find the mean of every n values in an R vector?
- How To Perform nCr (r-combinations) in Golang?
- An efficient way to check whether n-th Fibonacci number is multiple of 10?
- How to create a random vector for a range of values in R?
- How to create a table of frequency for range of values in an R data frame column?
- What is the most efficient way to deep clone an object in JavaScript?
- Program to find bitwise AND of range of numbers in given range in Python
- How to get the combinations for a range of values with repetition in R?

Advertisements