1. Introduction to problem
I am trying to find the number of monotonely increasing numbers with a certain number of digits. A monotonely increasing number with k
digits can be written as
n = a_0 a_1 ... a_k-1
where a_i <= a_(i+1)
for all i in range(0, k)
. A more concrete example are 123
or 12234489
. I am trying to create a function such that
increasing(2) = 45
increasing(3) = 165
increasing(4) = 495
increasing(5) = 1287
increasing(6) = 3003
Because there are 45 numbers with two digits that are increasing, 11, 12, ..., 22, 23, ..., 88, 89, 99
. And so forth.
I saw this as a nice opportunity to use recursion. I have tried to write a code that does this, however there is something wrong with the result. My psudo-code goes like this
2. Psudo-code
- Start with the numbers
[1, 2, ..., 9]
loop through these numbers. Increaselength
by one. - Loop over the numbers
[i, ..., 9]
wherelast_digit
was the number from the previous recursion. - If
length = number of digits wanted
add one tototal
andreturn
else repeat the steps above.
3. Code
global total
total = 0
nums = range(1, 10)
def num_increasing(digits, last_digit = 1, length = 0):
global total
# If the length of the number is equal to the number of digits return
if digits == length:
total += 1
return
possible_digits = nums[last_digit-1::]
for i in possible_digits:
last_digit = i
num_increasing(digits, last_digit, length + 1)
return total
if __name__ == '__main__':
num_increasing(6)
print total
4. Question:
Is my psudocode correct for finding these numbers? How can one use recursion correctly to tackle this problem?
I will not ask to find the error in my code, however some pointers or an example of code that works would be much obliged.