I'm using for-loops to iterate over two-dimensional list:
def itr(lpic, lH, lW, x, y):
'''lpic=2D-Array; lH=Row_count; lW=Column_count;'''
stack = []
range_x = range(x-1, x+2)
range_y = range(y-1, y+2)
append = stack.append
for i in range_x:
if 0<=i<lH:#i is a valid index *Updated
for j in range_y:
if (0<=j<lW) and (lpic[i][j]=="0"):
lpic[i][j] = "1"
append([i, j])
return stack
I'd like to know if there is a better way to do the same with Python2.5.
There are two simple optimizations for your code:
Use xrange instead for range. This will prevent from generation two temporary lists.
Use min and max in parameters for xrange to omit 'if' in outer loop. So you code will look like that:
def itr(lpic, lH, lW, x, y):
'''lpic=2D-Array; lH=Row_count; lW=Column_count;'''
stack = []
range_x = xrange(max(0,x-1), min(lH,x+2))
range_y = xrange(max(0,y-1), min(lW,y+2))
append = stack.append
for i in range_x:
for j in range_y:
if lpic[i][j]=="0":
lpic[i][j] = "1"
append([i, j])
return stack
This will slightly increase performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With