-3

Say you're given a tuple for the dimensions of an n-d array, i.e. (3,3) is a 3x3 matrix, (4,5,6) is a 4x5x6 matrix, etc. How can I write a function that can return a list of all indices possible?

 dimensions = (2,2)
 get_coordinates(dimensions)
 >>[[0,0],[0,1],[1,0],[1,1]]

or

 dimensions = (2,2,2)
 get_coordinates(dimensions)
 >>[[0,0,0],[0,1,0],[1,0,0],[1,1,0],[0,0,1],[0,1,1],[1,0,1],[1,1,1]]

1 Answers1

0

you could use a recursive approach:

def gen(t):
    if len(t) == 1:
        yield from range(t[0])

    else:   
        for e in range(t[0]):
            for g in gen(t[1:]):
                yield [e, *([g] if isinstance(g, int) else g)]

def get_coordinates(dim):
    return list(gen(dim))


print(get_coordinates((2, 2)))
print(get_coordinates((2, 2, 2)))

output:

[[0, 0], [0, 1], [1, 0], [1, 1]]
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0], [1, 0, 1], [1, 1, 0], [1, 1, 1]]
kederrac
  • 16,819
  • 6
  • 32
  • 55