python - How to find a given element in nested lists? -


this iterative solution:

def exists(key, arg):     if not arg:         return false     else:         element in arg:             if  isinstance(element,list):                 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, l.a. wants double recursive function solve this.

my attempt:

def exists(key, arg):     if not arg: //base case         return false     elif arg[0]==key: //if find key first trial         return true     else:         return (exists(arg[0:],key)) 

this doesn't work; shouldn't, because there no stop. also, not account lists of lists; don't know how that.

any answer, comment, etc. appreciated

if consider these cases:

  • my_list empty: key isn't found
  • my_list not list: key isn't found
  • my_list non-empty list (two cases):
    • my_list[0] key: found
    • otherwise, key in both my_list[0] , my_list[1:]

the code 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)             , len(my_list) > 0              , (my_list[0] == key                  or exists(key, my_list[0])                  or exists(key, my_list[1:]))) 

Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -