getting zeros from an integer using python recursion

Viewed 59

I want to extract all the zeros from a number and find the length of the number of zeros using Python recursion. I've tried the following code but it gives me an error. I can do that using for loop but I want to know how python recursion does this. For this code output should be 3.

def zeros(n):
    x = list(str(n))
    if x == []:
        return []
    else:
        head = x[0]
        tail = "0"
        return len([head]) + zeros(tail)


print(zeros(10010))

RecursionError: maximum recursion depth exceeded while calling a Python object

3 Answers

because after first loop , head is always a scalar value (number) and tail is always 0 , so always the else part of your logic runs and there is no logic to stop the recursion for a specific condition, and eventually it hits the recursion limit with the error message you got.

you can count number of occurrence of zeros in a number this way easily:

print(str(10010).count('0'))

you don't need recursion to solve this problem really.

If, for some reason, you don't like the simplicity of using count as already suggested and REALLY want to use recursion, the following code works:

def zeros(n):
    n = str(n)
    if not len(n): 
        return 0
    elif n[0] == '0':
        return 1 + zeros(n[1:])
    else:
        return zeros(n[1:])

No need for strings, just arithmetic:

def zeros(n):
    if n == 0:
        return 1
    else:
        if n < 0:
            n = -n
        nb_zeros = 0
        while n > 0:
            n, u = divmod(n, 10)
            if u == 0:
                nb_zeros += 1
        return nb_zeros

# TESTING
for n in 0, 8, 100, 10010:
    print('{:6d} --> {}'.format(n, zeros(n)))

# OUTPUT
#      0 --> 1
#      8 --> 0
#    100 --> 2
#  10010 --> 3

Explanation: we repeatedly extract and remove the unit digit. For instance, if:

n == 1037

then:

n, u = divmod(n, 10)

results in:

n == 103, u == 7
Related