Generate grid of coordinate tuples

Viewed 68

Assume a d-dimensional integer grid, containing n^d (n >= 1) points.

I am trying to write a function that takes the number of domain points n and the number of dimensions d and returns a set that contains all the coordinate points in the grid, as tuples.

Example: intGrid (n=2, dim=2) should return the set:

{(0,0), (0,1), (1,0), (1,1)}

Note: I cannot use numpy or any external imports.

1 Answers

Python has a good set of built-in modules that provides most of the basic functionality you will probably need to start getting your things done.

One of such good modules is itertools, where you will find all sorts of functions related to iterations and combinatorics. The perfect function for you is product, that you can use as below:

from itertools import product

def grid(n, dim):
  return set(product(range(n), repeat=dim))

print(grid(2, 2))
# {(0, 0), (0, 1), (1, 0), (1, 1)}

print(grid(2, 3))
# {(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)}
Related