Here’s what I want to write:
groups[m][n] = groups[m - 1][n] or ++gid
Here’s what I have to write:
g = groups[m - 1][n]
if g:
groups[m,n] = g
else:
gid += 1
groups[m][n] = gid
Is there no more compact way of writing that in Python simply because it lacks a ++ operator?
A larger sample from a method I’m working on:
groups = [[0] * self.columns] * self.rows
gid = 0
for m in xrange(self.rows):
for n in xrange(self.columns):
stone = self[m, n]
if stone == self[m - 1, n]:
if groups[m - 1][n]:
groups[m][n] = groups[m - 1][n]
else:
gid += 1
groups[m][n] = gid
elif stone == self[m, n - 1]:
if groups[m][n - 1]:
groups[m][n] = groups[m][n - 1]
else:
gid += 1
groups[m][n] = gid
I think it’s a lot harder to read when I have to blow it out like that, plus I’m evaluating m-1 twice… I’m not sure how I can condense it though.
This is what I came up with:
I created a wrapper class around int:
class Int(object):
def __init__(self, i):
self.i = i
def pre(self, a=1):
self.i += a
return Int(self.i)
def post(self, a=1):
cpy = Int(self.i)
self.i += a
return cpy
def __repr__(self):
return str(self.i)
def __nonzero__(self):
return self.i != 0
Which can be used like this:
def group_stones(self):
groups = [[None for _ in xrange(self.cols)] for _ in xrange(self.rows)]
gid = Int(0)
for m in xrange(self.rows):
for n in xrange(self.cols):
stone = self[m, n]
if stone == self[m - 1, n]:
groups[m][n] = groups[m - 1][n] or gid.pre()
elif stone == self[m, n - 1]:
groups[m][n] = groups[m][n - 1] or gid.pre()
else:
groups[m][n] = gid.pre()
Much like I would do in other languages.
You can add some “magic” to your Int class: