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
CodePudding user response:
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.
CodePudding user response:
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:])
