I have data about arrays that each have different dimensions. This data looks like this:
spatial_dimensions = {
'x': 5,
'y': 2,
'z': 4
}
Another array could be described like this:
table_dimensions = {
'rows': 10,
'columns': 5
}
I also have data about what slots are taken in each array. That is expressed like this for the data pertaining to the spatial_dimensions
array:
occupied_slots = [
[1,2,3],
[4,2,2],
[1,1,1]
]
For the table_dimensions
array it could e.g. be
occupied_slots = [
[2,3],
[5,2],
[6,1],
[5,5]
]
I don't have the "full" arrays, only their dimensions and a list of occupied slots.
I want to randomly get an empty slot from an array and return it as a list (that list describes the location in the array).
In the above examples, a random empty slot could be [1, 2, 2]
and [4, 3]
respectively.
I want to do this in pure Python. I don't want to use numpy as it would introduce a dependency on my project only for this specific issue.
I'm stuck at finding a way of finding an empty slot without re-creating the whole array in memory and filtering out the occupied slots, as I'm afraid that will be too expensive. Especially since there is no limit on the array dimensions.
PS -- This is not an assignment I got; I tried to abstract away all the project details in this question.
Update
I'm currently using this code (based on How to iterate over this n-dimensional dataset?):
import itertools
import random
dimensions = {
'x': 2,
'y': 4,
'z': 3
}
occupied = [
[2,3,1],
[1,1,1]
]
loopover = [range(1, i + 1) for i in [dimensions[key] for key in dimensions.keys()]]
print(random.choice([i for i in itertools.product(*loopover) if list(i) not in occupied]))
As @ekhumoro commented, this recreates the whole array in memory before passing it to random.choice()
which is indeed what I'd like to avoid.