grouping array

Michael Spencer mahs at telcopartners.com
Fri Sep 30 12:34:46 EDT 2005


pkilambi at gmail.com wrote:
> fredrick's solutions seems to be more closer to what I was looking
> for.But I am still not sure if that could be done without the use of
> Image module.

What do you mean by "closer to what I was looking
for"?  For the single test case you provided:

 > say x = [[2,2,0,0,1,1],
 >          [1,1,0,0,1,1],
 >          [1,1,0,0,1,1]]
 > I basically want to group regions that are non zero like I want to get
 > the coordinates of non zero regions..as (x1,y1,x2,y2)
 > [(0,0,2,1),(0,4,2,5)] which show the top left(x1,y1) and bottom
 > right(x2,y2) corners of each group.hope i am clear.
 >


my solution provides the correct output:

   >>> x = [[2,2,0,0,1,1],
   ...      [1,1,0,0,1,1],
   ...      [1,1,0,0,1,1]]
   ...
   ...
   >>> getregioncoords(x)
   [((0, 0), (2, 1)), ((0, 4), (2, 5))]

* except that the points aren't flattened.  If that's important to you, rewrite 
getregioncoords as follows:

def getregioncoords(grid):
     """Get top left and bottom right of *rectangular* regions"""
     regions = getregions(grid)
     return [reg[0]+reg[-1] for reg in regions if reg.sort() or True]

  >>> getregioncoords(x)
  [(0, 0, 2, 1), (0, 4, 2, 5)]
  >>>


> Also in your solution I cannot follow this

I broke the solution into two parts:

1) the getregions generator yields a list of all the contiguous regions.  The 
output below is the lists of coordinates that are contiguous non-zero cells in 
the grid.

 > [[1, 1, 2, 1, 2, 0],
 >    [2, 0, 0, 2, 0, 1],
 >    [1, 2, 2, 0, 2, 0],
 >    [0, 1, 0, 0, 0, 0],
 >    [2, 0, 0, 1, 1, 0],
 >    [2, 2, 2, 0, 1, 0]]
 >   >>> print "\n".join(str(reg) for reg in getregions(x))
 >   [(0, 1), (0, 0), (0, 2), (1, 0), (0, 3), (2, 0), (1, 3), (0, 4), (2,
 > 1), (3,
 > 1), (2, 2)]
 >   [(5, 4), (4, 4), (4, 3)]
 >   [(5, 0), (5, 1), (4, 0), (5, 2)]
 >   [(1, 5)]
 >   [(2, 4)]


2) If the regions are rectangular, the getregioncoords functions returns the 
coordinates of the top-left and bottom-right points.  You did not answer the 
previous post which asked what to do if the regions were not rectangular.



HTH

Michael






More information about the Python-list mailing list