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
xrangeinstead forrange. This will prevent from generation two temporary lists.Use
minandmaxin parameters forxrangeto omit ‘if’ in outer loop. So you code will look like that:This will slightly increase performance.