user927584
user927584

Reputation: 395

Python: returning the cell coordinates

I am stuck on writing a function that takes in an integer value of the size that will return all the cell coordinates.

For example: if the size is 1 then it will return (0,0). If the size is 2, then it will return (0,0), (0,1), (1,0), (1,1)

This is what I have done so far

def get_cells(size):

    for x_axis in range(0, size):
        x = x_axis
        for y_axis in range(0, size):
            y = y_axis
    return (x, y)

This code only returns the very last cell coordinate... How would I make it to return all the cell coordinates in a dictionary?

Upvotes: 0

Views: 1529

Answers (4)

unutbu
unutbu

Reputation: 879691

You could use:

def get_cells(size):
    result = []
    for x_axis in range(size):
        for y_axis in range(size):
            result.append((x_axis, y_axis))
    return result

which could be further simplified (using a list comprehension) to:

def get_cells(size):
    return [(x_axis, y_axis) for x_axis in range(size) for y_axis in range(size)]

which could be further simplified (using itertools.product) to:

import itertools as IT
def get_cells(size):
    return list(IT.product(range(size), repeat=size))

Note that it is not really necessary to define a function for this at all, since the result is just a one-liner. You could use IT.product(range(size), repeat=size) directly instead of defining get_cells.


In [1]: import itertools as IT

In [2]: list(IT.product(range(2), repeat=2))
Out[2]: [(0, 0), (0, 1), (1, 0), (1, 1)]

Upvotes: 2

fredtantini
fredtantini

Reputation: 16556

you can:

create a new list (l = []), and append the coordinates to the list (l+=[x, y])

>>> def get_cells(size):
...     l = []
...     for x_axis in range(0, size):
...         x = x_axis
...         for y_axis in range(0, size):
...             y = y_axis
...             l.append([x, y])
...     return l
...
>>> l = get_cells(2)
>>> l
[[0, 0], [0, 1], [1, 0], [1, 1]]

Or use yield instead of return to be able to iterate over your cells:

>>> def get_cells(size):
...     for x_axis in range(0, size):
...         x = x_axis
...         for y_axis in range(0, size):
...             y = y_axis
...             yield (x, y)
...
>>> for i in get_cells(2):
...   print i
...
(0, 0)
(0, 1)
(1, 0)
(1, 1)

Upvotes: 0

dirkster
dirkster

Reputation: 522

You could try

  [(x,y) for x in xrange(0, size) for y in xrange(0, size)]

or

  ((x,y) for x in xrange(0, size) for y in xrange(0, size))

assuming you mean to return an iterable, not a dict.

Upvotes: 0

Tamim Shahriar
Tamim Shahriar

Reputation: 739

I think you would prefer a list instead of a dictionary to contain all the co-ordinates as tuples.

def get_cells(size):
    my_list = []
    for x_axis in range(0, size):
        x = x_axis
        for y_axis in range(0, size):
            y = y_axis
            my_list.append((x, y))
    return my_list

Upvotes: 0

Related Questions