need some assistance with my recursive function

Viewed 41

Write a recursive function count(x, s), which counts and returns how many times x is at the highest level in the list s. Example: The call count(4, [1, 4, 2, ['a', [ [ 4 ] , 3, 4] ] ] ) should return 1.

here's my code:

def count(x, l):
     if type(l) != list:
         return None
     elif l[0] == x:
         return 0
     else:       
        i = count(x, l[1:])        
        if i is not None:
            return  1 + i                     
        return None


if __name__ == "__main__":
    l = [1, 4, 2, ['a', [ [ 4 ] , 3, 4] ] ]
    print(count(4, l))

In the given example, it works fine. It returns 1 as it should. But when I try to do some test cases, it fails. I'll provide the test cases down below. Any lead on what I am doing wrong here would be appreciated. Thanks in advance

l = [1, 'a', 3, 7, 1, [1, 4]]  #list
count('a', l)                  #should return 1
count(1, l)                    #should return 3
count(4, l)                #should return 1
count([1, 4], l)           #should return 1
count('x', l)              #should return 0

P.s can't use any builtin libraries.

1 Answers
def count(x,l,n=0):
    r=[]
    for v in l:
        if x == v:
            n+=1
        else:
            if type(v) in (tuple,list):
                r.append(v)
    while r:
        return count(x,r.pop(),n=n)

    return n

             


if __name__ == "__main__":
    l = [1, 4, 2, ['a', [ [ 4 ,2,5,[[],[4,[4]]]] , 3, 4] ] ]
    print(count(4, l))

           
Related