Leo wahyd Leo wahyd - 2 months ago 13
Python Question

How to find a given element in nested lists?

This is my iterative solution:

def exists(key, arg):
if not arg:
return False
else:
for element in arg:
if isinstance(element,list):
for i in element:
if i==key:
return True
elif element==key:
return True
return False
print(exists("f", ["a", ["h", "e", "j"], ["t", "e", "s", "c", "o"]]))


However, my L.A. wants a double recursive function to solve this.

my attempt:

def exists(key, arg):
if not arg: //base case
return False
elif arg[0]==key: //if we find the key from the first trial
return True
else:
return (exists(arg[0:],key))


This doesn't work; it shouldn't, because there is no stop. Also, it does not account for lists of lists; I don't know how to do that.

Any answer, comment, etc. is appreciated

Answer

If we consider these cases:

  • my_list is empty: the key isn't found
  • my_list is not a list: the key isn't found
  • my_list is a non-empty list (two cases):
    • my_list[0] is the key: it was found
    • otherwise, look for the key in both my_list[0] and my_list[1:]

the code would be

def exists(key, my_list):
    if not isinstance(my_list, list) or not my_list:
        return False

    return (my_list[0] == key
            or exists(key, my_list[0]) 
            or exists(key, my_list[1:]))

or even

def exists(key, my_list):
    return (isinstance(my_list, list)
            and len(my_list) > 0 
            and (my_list[0] == key
                 or exists(key, my_list[0])
                 or exists(key, my_list[1:])))
Comments