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.