I have created a recursive algorithm to count the number of times a certain n
appears in a ls
list. It seems to work if the ls
list is quite small (between 10 and 100), but if it is large, type 1000, it does not 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...!")