I'm trying to make a function that tries to find a variable in multiple (unspecified amount) of layers of lists.
for example:
if a list is something like : ['a',3,'c',['e',['z',6],['r',8,'t']],'z']
and want to find the index of 6
I would get : [3][1][1]
if a list is something like : [1,2,[3,4],5]
and want to find the index of 3
I would get : [2][0]
I would be happy if somebody helped me with this thing, been trying for 3 days... (new at coding)
CodePudding user response:
IIUC, here is a simple recursive function to find the first matching element:
l = ['a',3,'c',['e',['z',6],['r',8,'t']],'z']
def find(l, item):
for i,e in enumerate(l):
if isinstance(e, list):
if (out:=find(e, item)): # python ≥ 3.8, below split in two lines
return [i, *out]
elif e == item:
return [i]
Example:
find(l, 6)
[3, 1, 1]
find([1,2,[3,4],5], 3)
[2, 0]
find(l, 'missing') # no output
CodePudding user response:
You can either use DFS or BFS to search for your element. Without knowing the specifics of your language of choice, this is how the pseudo code would look like for BFS:
Initialize a integer level
variable
Initialize a list of 'listOfLevel' list
- Initialize a queue. Add the input list to the queue.
- Do this while the queue is not empty:
- Remove all the elements from the queue and process them one at a time:
- Mark the index of the element and collect it into 'listOfLevel'
- Iterate over the array:
a. if the element is a list, add it to the queue.
b. if the element is a number, compare it with the target.- If the number is same as target; break out.
- Go to step 2.
At the end you will have all the indices in the 'listOfLevel'.
Note, this algorithm would stop after it finds the first occurrence of the target and then stop.