0
Is this the best way to count the amount of elements recursively?
Is this the best way to count the amount of elements recursively? def foo(l): if not l: return 0 del l[0] return foo(l) + 1 a = [1, 2, 3] print(foo(a))
5 odpowiedzi
+ 1
It is, but you can't use the list a after calling foo
+ 1
Answer from Stack Overflow
b = ['d']
c = ['e', 'f']
h = []
a = [b,c,h]
def recur(l,call=1):
if not l:
return 0
else:
print("l = {} and l[0] = {} on recursive call {}".format(l,l[0],call))
call+=1
return recur(l[1:],call) + len(l[0])
+ 1
I can't say if it's the best one, but it's simple.
after calling method foo the list will be empty, which means refilling the list.
0
Well, I made this:
def foo(l,num=0):
try:
l[num]
return foo(l,num+1)
except:
return num
a = [1,2,3]
print(foo(a))
print(a)
0
The list will also be available