-3

I have a nested list and my assignment is to find, where it is in a nested list. For example, if list=["a",["b","c"]], then search(list,"b") should return 2. If there isn't such string in any depth, then the function should return -1. So far I have a code which returns True/False depending on whether or not the string is in a list. How can I go about counting the depth?

  • is `2` the index of "b" in the flattened list plus one or the depth of "b" itself? – Ajax1234 Jan 08 '18 at 21:21
  • 1
    Please, can you post some code of the things you've tried ? – IMCoins Jan 08 '18 at 21:23
  • Please share the code which you have. and what does this value 2 represent? Is it the position in the overall list (ignoring nested structure), depth of nest list, or index of list in which it is present? *(your sample example is bad, please give clearer example)* – Moinuddin Quadri Jan 08 '18 at 21:23
  • How about the list `[2,[[3,1],6.7,[2,1,6],8,["C",2,7,[[[1]],2]]`? It's got duplicate values, multiple levels of nesting, and diverse datatypes inside. – Jakob Lovern Jan 08 '18 at 21:26
  • 2
    It is bad practice to name a python variable `list`. For example, `list=5` will cause `list(set([1,1,2]))` to return `TypeError: 'int' object is not callable` – user3483203 Jan 08 '18 at 21:26
  • Could you flatten the list (see [here](https://stackoverflow.com/a/952952/8954291)) and then use some sort of search (see [here](https://stackoverflow.com/a/17202481/8954291)) to find the indices of the appropriate values? – Jakob Lovern Jan 08 '18 at 21:31

1 Answers1

0

If you are searching for the depth of the target character, you can use recursion with a list comprehension:

def search(data, target, level):
   if target in data:
       return level
   levels = 0
   for row in filter(lambda x:isinstance(x, list), data):
       levels += search(row, target, level+1)
   return levels

val = search(['a', ['b', 'c']], 'b')
result = -1 if not val else val

Output:

2

However, if you are trying to find the index at which the target value exists, you can try this:

def flatten(l, target=str):
   if isinstance(l, target):
       yield l
   else:
       for i in l:
           for b in flatten(i):
              yield b

def search(data, target):
   new_list = list(flatten(data))
   return new_list.index(target)+1
print(search(['a', ['b', 'c']], 'b'))

Output:

2
Ajax1234
  • 69,937
  • 8
  • 61
  • 102