Performance Issues please help
Michael Spencer
mahs at telcopartners.com
Thu Jun 2 14:15:36 EDT 2005
Michael Spencer wrote:
> def search1(m):
> box = {}
> for r,row in enumerate(m):
> for c,e in enumerate(row):
> try:
> minc, minr, maxc, maxr = box[e]
> box[e] = ( c < minc and c or minc,
> r < minr and r or minr,
> c > maxc and c or maxc,
> r > maxr and r or maxr)
> except KeyError:
> box[e] = (c, r, c, r)
> return box
>
> Michael
>
Sorry, my earlier solution was incorrect since:
c < minc and c or minc # evaluates to minc if c == 0
Two of the tests are unnecessary, as pointed out by Peter
The remaining test:
c > maxc and c or maxc
does not suffer from the same problem, since c cannot both be 0 and greater than
maxc
The following version, still untested ;-) has the correction:
def search2(m):
box = {}
for r,row in enumerate(m):
for c,e in enumerate(row):
try: # use this form if e will be found 90%+ of the time
# otherwise, use: if e in box:
minc, minr, maxc, maxr = box[e]
# note correction for c == 0
# also Peter's simplification
box[e] = ( c and (c < minc and c or minc),
minr,
c > maxc and c or maxc,
r)
except KeyError:
box[e] = (c, r, c, r)
return box
Michael
More information about the Python-list
mailing list