Home > Software engineering >  Recursion for checking an occurrence of a certain digit (no loops only recursion required)
Recursion for checking an occurrence of a certain digit (no loops only recursion required)

Time:11-30

This is my code:

def helper_number_of_ones(n:int, counter:int)->int:
    if n == 1:
        counter  = 1
        return counter
    else:
        if n % 10 == 1:
            counter  = 1
        if n // 10 == 1:
            counter  = 1
    return helper_number_of_ones(n-1,counter)

def number_of_ones(n: int) -> int:
    count = 0
    return helper_number_of_ones(n,count)

My code basically checks for the number of digit one occurrences, throughout all numbers between n and 1, for example n=13 will output 6 for 6 ones occurrences, the only problem it doesn’t work properly for numbers bigger than 100? Thanks in advance

CodePudding user response:

Your code takes into consideration two possibilities:

  1. The ones digit is 1 (if n % 10 == 1)
  2. The tens digit is 1 (if n // 10 == 1)

This is enough for numbers up to 99, but fails for higher numbers.

I would suggest to break your function into two separate functions: one that counts the number of occurences of 1 in a single number, and another that does that for a range of numbers (using the first one of course).

CodePudding user response:

It is because of how you calculate counter

...
        if n % 10 == 1:
            counter  = 1
        if n // 10 == 1:
            counter  = 1
...

For example, if n = 100, it will fail both ifs. You can make a function that calculates the number of 1 in a number recursively.

def num_of_one(number):
    if number == 0:
        return 0
    else:
        return ((number % 10) == 1)   num_of_one(number // 10)

Then make another function to calculate it over the range.

def range_num_of_one(max_num):
    if max_num == 1:
        return 1
    else:
        return num_of_one(max_num)   range_num_of_one(max_num - 1)
  • Related