You can do something much simpler, like:
def size(lst):
if type(lst) == int:
return 1
else:
return 1 + sum(size(e) for e in lst)
print size([[[14],[23,[14]]]])
Domanda
I need to write a function(size) that gets a list structure and recieves its size. The size is the number of pair brackets and the number of ints in the list structure. For example: size([[[14],[23,[14]]]])= 8 (5 pair brackets, 3 ints)
I wrote a code but I cant find a way that cnt won't assign to zero each time I call the recursion. This is my code:
def flatten(lst):
if type(lst)==int:
return [lst]
elif lst==[]:
return []
else:
return sum(([x] if not isinstance(x, list) else flatten(x) for x in lst),[])
def size(lst):
cnt=0
if lst== []:
return 1
if type(lst)== int:
return 1
b= str(lst)
ind= b.find('[')
while ind!=-1:
cnt+=1
lst=lst[ind+1:]
return cnt+ size(lst)
return cnt+ len(flatten(lst))
Soluzione
You can do something much simpler, like:
def size(lst):
if type(lst) == int:
return 1
else:
return 1 + sum(size(e) for e in lst)
print size([[[14],[23,[14]]]])