Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getting zeros from an integer using python recursion

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading