3
I created a recursive algorithm to count the number of times a certain number n
appears in a list ls
. It seemed to work if the list ls
is quite small (between 10 and 100), but if it’s big, like 1000, it doesn’t seem to work anymore: it enters an infinite recursion...
Can anyone understand why?
def _count(n, ls, index):
if index < len(ls):
if ls[index] == n:
return 1 + _count(n, ls, index + 1)
else:
return _count(n, ls, index + 1)
return 0
def count(n, ls):
"""Counts how many times n appears in the list or tuple ls."""
return _count(n, ls, 0)
if __name__ == "__main__":
from random import randint
for i in range(10):
ls = [randint(0, 10) for _ in range(1000)] # modifica 1000 para 100 para funcionar
print("List:", ls)
r = randint(0, 10)
print("Counting number:", r)
c = count(r, ls)
print("Counted:", c)
if c != ls.count(r):
raise Exception("Something is wrong with the implementation of count...!")
The recursion limit is for all functions of your program and this includes the main, the call to
count
, the call tolen
inindex < len(xs)
, etc. If you givesys.setrecursionlimit
for a little number you can see it clearly.– hugomg