zeyuxie zeyuxie - 8 months ago 72
Python Question

a recursion function that return an int

def nested_count(l : 'any nested list of int', a : int) -> int:
c = 0
while len(l) != 0:
for x in l:
if type(x) == int:
if x == a:
c = c + 1
elif type(x) == list:
return c

this function passed a nested list of ints and a single int as arguments; it returns the number of times the single int argument appears in the nested list argument, for example:

nested_count( [[1,2,[4,[1],8],[1,3,2]],[1,1]], 1 )

returns 5

I am not sure why my function does not work

can someone tell me how to fix it? many thanks.


You are not adding nested_count results to c:

def nested_count(lst, l):
    c = 0
    for i in lst:
        if i == l:
            c += 1
        elif type(i) == list:
            c += nested_count(i, l)
    return c

Also it is better to iterate over list with for.