Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Nested Lists

I'm having trouble getting my head around a problem on recursive nested lists. The problem; need to define a procedure to access a nested list to an arbitrary depth. It would take an nested list and an index, and return the part of the list at that index. From this given function, recursively find the value at the given index.

For example

Well here is a better visual representation. To select the element 9 out of it, we need to do something like nested[3][1]

    nested = \
    [[[1, 2],
      3],
     [4,
      [5, 6]],
     7,
     [8, 9, 10]]

recursive_func(nested_list, [3,1]) #recursive function definition, the second argument is the index at which the data needs to be retrieved.  
>>> 9 #so given the function an index of [3,1] would return 9

Any help to point me in the right direction would be grateful

like image 987
Benji Avatar asked Nov 28 '25 07:11

Benji


1 Answers

This may do you, but I'm still not 100% sure what you are looking for...

>>> def findItem(nested, pos):
    if pos[0] == 1:
        return nested[pos[1]-1]
    else:
        nextLevelDown = []
        for item in nested:
            if type(item) == type([]):
                nextLevelDown = nextLevelDown + item
        return findItem(nextLevelDown, [pos[0]-1, pos[1]])

>>> findItem([[[1, 2], 3], 4], [3, 1])
1
>>> findItem([[[1, 2], [3]], 4], [3, 3])
3
>>> findItem([[[1, 2], [3]], 4], [2, 2])
[3]

UPDATE: So after much back and forth, I finally understand the question, and it is much simpler than it originally seemed, all you need is:

>>> def recursiveRef(nested, idxList):
    if len(idxList) > 1:
        return recursiveRef(nested[idxList[0]], idxList[1:])
    return nested[idxList[0]] 

>>> recursiveRef([[[1, 2], 3], [4, [5, 6]], 7, [8, 9, 10]], [3, 1])
9
like image 110
verdesmarald Avatar answered Nov 29 '25 20:11

verdesmarald



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!