3 Replies - 750 Views - Last Post: 21 January 2012 - 06:14 PM Rate Topic: -----

Topic Sponsor:

#1 jone kim  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 30
  • Joined: 07-January 10

PYTHON: get the index of empty squares in the grid

Posted 21 January 2012 - 08:59 AM

I've made a 2*2 grid.
grid = [[0,0],[0,0]]

initially, the gird is empty. Now after filling the grid with some values, I want the index of the empty regions in the grid.

For example, an user fills the grid @ positions: grid[ col1 ][ row1 ] and grid[ col2 ][ row2 ]. now I want the list of empty boxes in the grid.

How can I do it? I can figure out how to do this in Python. Can anyone help me?
Is This A Good Question/Topic? 0
  • +

Replies To: PYTHON: get the index of empty squares in the grid

#2 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 443
  • View blog
  • Posts: 792
  • Joined: 08-June 10

Re: PYTHON: get the index of empty squares in the grid

Posted 21 January 2012 - 09:34 AM

The simplest way would be with nested loops:
for i in range(len(grid)):
    for j in range(len(grid[i])):
        if grid[i][j] == 0:
            print("Position (%i, %i) is zero." % (i, j))


This post has been edited by Motoma: 21 January 2012 - 09:35 AM
Reason for edit:: Edited for punctuation.

Was This Post Helpful? 2
  • +
  • -

#3 jone kim  Icon User is offline

  • New D.I.C Head

Reputation: 2
  • View blog
  • Posts: 30
  • Joined: 07-January 10

Re: PYTHON: get the index of empty squares in the grid

Posted 21 January 2012 - 05:18 PM

Thank You Motoma for the help.

How to put the index of the empty grid in a list?

grid = [[0,0],[0,0]]
user fills the grid @ positions: grid[ col1 ][ row1 ] and grid[ col2 ][ row2 ].

I want the output: emptyGrid = [1,2]

I've written the code but do not know will it work or not. Please check the code.

def get_emptygrid(grid, row, col):
    for i in range(len(grid)):
        for j in range(len(grid)):
            if grid[i][j] == 0:
                print('Position (%i,%i) is zeo' %(i,j))
                emptyGrid = [grid[i][j]]
                for x in range (emptyGrid):
                    emptyGrid.append(input())


Was This Post Helpful? 0
  • +
  • -

#4 Motoma  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 443
  • View blog
  • Posts: 792
  • Joined: 08-June 10

Re: PYTHON: get the index of empty squares in the grid

Posted 21 January 2012 - 06:14 PM

You're code is not quite right. What are row and col supposed to be?

If you want to return a list of indexes that are empty (zero), it would look something like this:

def get_emptygrid(grid, row, col):
    empties = []
    for i in range(len(grid)):
        for j in range(len(grid[i])):
            if grid[i][j] == 0:
                empties.append((i, j))
    return empties

...
grid = [[0,2],[10,0]]
print("Empties: %r" % (empties))


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1