Jasmine N
Jasmine N

Reputation: 91

recursive to find number of nested list and element value if depth reaches 0

I have a nested list and I want to return the number of nested list (or the depth) and the element value if the depth reaches 0. For example, with below nested list, the value I want to return is (13, 37). But my code returns 36 only.

nested = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[13]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]

def search(a, depth=0):
    count = 0
    for e in a:
        if isinstance(e, list):
            count = count + 1 + search(e)
    return count
    
search(nested)

How should correct my code to make it return (13, 37) as expected?

Upvotes: 4

Views: 1015

Answers (4)

Ajax1234
Ajax1234

Reputation: 71471

You can use a recursive generator function to handle inputs with more than one non-list element:

def search(d, c = 0):
   for i in d:
      if not isinstance(i, list):
         yield (i, c)
      else:
         yield from search(i, c+1)


nested = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[13]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
print(list(search(nested)))

Output:

[(13, 36)]

Upvotes: 0

pakpe
pakpe

Reputation: 5489

A good recursive function has a base case and a recursive case. Ruswick's (good) answer can be modified to meet these criteria:

def search(a, depth=0):
    if type(a) is int: #base case
        return a, depth
    return search(a[0], depth + 1) #recusive case

print(search(nested))
#(13, 37)

Upvotes: 1

Arne
Arne

Reputation: 10545

You're not counting the outermost list. To correct this, pull the list check outside of the loop. To return the inner value, retrieve it when the list element is not a list anymore:

def search(a):
    count = 0
    if isinstance(a, list):
        count += 1
        for e in a:
            inner_value, count_inc = search(e) 
            count += count_inc
    else:
        inner_value = a
    return inner_value, count

Upvotes: 1

Dan Ruswick
Dan Ruswick

Reputation: 3170

This gives the right answer for a single value wrapped in a single set of lists. Not sure why you are iterating over the elements of the list. Are there potentially multiple nested sub lists/values?

nested = [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[13]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
def search(a, depth=0):
  if type(a) is list:
     return search(a[0], depth + 1)
  else:
    return a, depth
    
print(search(nested))

Upvotes: 2

Related Questions