Paul Lynn
Paul Lynn

Reputation: 99

Dynamic multidimensional list in Python

I want to create function which can insert a given value to a given index into a given array. It's quite simple with two-dimensional arrays:

def insertInto(index, array, value):
    are index in array?
        no:
            iterate over range (len(array) -> index):
                insert None into array
    insert value into array
    return array

But what, if I want to do the same trick with multidimensional index?

Suppose, we have arr = [] at the beginning. Then after executing insertInto((0,0,2), arr, 'yey') given arr should look like [[[None, None, 'yey']]], and arr[0][0][2] == 'yey'.

I've tried to make such function, but it's hard to go into new dimensionality level. My idea was:

def insertInto(index: tuple, array, value):
    currentCoordinate = index.pop(0)
    currentLevel = array[currentCoordinate]
    while index:  # while len(index) > 0
        if size(array[i]) < currentCoordinate:
            currentLevel = enlargeList(currentLevel, currentCoordinate)
            # enlargeList function enlarge the given list, so it will
            # have required index. the gaps will be filled with None
            # example: enlargeList([1], 3) == [1, None, None, None]
        currentLevel[currentCoordinate] = []
        currentLevel = currentLevel[currentCoordinate]
        # in the next iteration currentLevel variable will be equal to
        # inserted list
        currenCoordinate = index.pop(0)

The problem with this solution very obvious: I can't assign (for example) a = l[0] (where l is a list and a is some temporary variable) and then modify a, because it will not affect l (see this question).

Does anybody have an idea how to do this another way?

This code should not require any libraries.

Upvotes: 0

Views: 462

Answers (1)

sknat
sknat

Reputation: 478

A way to simplify the problem would be to use recursive functions. That way variables stay in the scope and shouldn't erase each other.

I did use (index, *tail) instead of a tuple based index for simplicity

def ensure_array_index(array, index):
    while len(array) <= index:
        array.append(None)
    if array[index] is None:
        array[index] = []

def insert_into(array, value, index, *tail):
    ensure_array_index(array, index)
    if len(tail) == 0:
        array[index] = value
    else:
        insert_into(array[index], value, *tail)


arr = []
insert_into(arr, '001', 0, 0, 1)
insert_into(arr, '011', 0, 1, 1)
insert_into(arr, '211', 2, 1, 1)
insert_into(arr, '1', 1)
print arr

>>> [[[None, '001'], [None, '011']], '1', [None, [None, '211']]]

The only drawback is that you're limited by the python callstack for the depth you can insert (~100 afaik)

Upvotes: 1

Related Questions