Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to count n digit integers where digits are strictly increasing in Python
Suppose we have a number n, we have to find the number of n-digit positive integers such that the digits are in strictly increasing order.
So, if the input is like n = 3, then the output will be 84, as numbers are 123, 124, 125, ..., 678, 789.
Understanding the Problem
For n-digit numbers with strictly increasing digits, we need to choose n different digits from {1, 2, 3, ..., 9}. We cannot use 0 as the first digit in an n-digit number. This becomes a combination problem: C(9, n).
Algorithm
To solve this, we will follow these steps −
-
if n ? 9 and n > 0, then
return Combination C(9, n)
-
otherwise,
return 0
Implementation Using math.factorial
Let us see the following implementation to get better understanding −
from math import factorial
class Solution:
def solve(self, n):
if 0 < n <= 9:
return factorial(9) // factorial(n) // factorial(9 - n)
else:
return 0
ob = Solution()
print(ob.solve(3))
The output of the above code is −
84
Using math.comb Function
Python 3.8+ provides a built-in combination function that's more readable −
from math import comb
class Solution:
def solve(self, n):
if 0 < n <= 9:
return comb(9, n)
else:
return 0
ob = Solution()
print(f"n = 3: {ob.solve(3)}")
print(f"n = 4: {ob.solve(4)}")
print(f"n = 9: {ob.solve(9)}")
print(f"n = 10: {ob.solve(10)}")
The output of the above code is −
n = 3: 84 n = 4: 126 n = 9: 1 n = 10: 0
How It Works
For n = 3, we choose 3 digits from {1, 2, 3, 4, 5, 6, 7, 8, 9}. The combinations are C(9, 3) = 84. Some examples include 123, 145, 678, 789, etc. Since digits must be strictly increasing, there's only one way to arrange the chosen digits.
Conclusion
The problem reduces to calculating combinations C(9, n) since we select n digits from 9 available digits (1-9). Use math.comb() for cleaner code or calculate manually using factorials.
