
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find NCR Values for R in Range 0 to N 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]
Advertisements