Python Forum

Full Version: How to avoid slow cursor operations?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi. I'm using numpy as np. I have a 2D array called CC of all zeros and ones. For every one in CC, I want to change all adjacent array values to one. I want to do this recursively, and then I want to count how many steps it takes for the last zero to disappear. That is the point of the code: how far away from a one is the farthest zero. I initialized CC with
CC = np.zeros((N,N),dtype="int")  
and then I wrote some ones into it. My first idea was to make 8 copies of CC, each with the values shifted by one, (eight copies for up/down,left/right, and 4 diag) and then add those copies to CC, and then iterate. However, all the shift commands I found like roll do not shift the entire array but they send the end of each line to the beginning of the next. As it is, if CC is 1000 x 1000, then I have the below cursor doing ~eight operations for one million times. There must be a better way!
MAX_RADIUS = 0
nn = 0
CCtmp = np.zeros((N,N),dtype="int") 
while nn < 1:
    for i in range(len(CC)-1):
        for j in range(len(CC)-1):
            if i**2+ j**2 > N**2:         ## Condition for the part of CC I don't care about
                CCtmp[i,j] = 1
            if (CC[i,j] == 1 ): 
                    CCtmp[i+1,j] = 1  ## For every black pixel, color adjacent black
                    CCtmp[i,j+1] = 1  
                    CCtmp[i+1,j+1] = 1   
                    CCtmp[i-1,j] = 1
                    CCtmp[i,j-1] = 1  
                    CCtmp[i-1,j-1] = 1   
                    CCtmp[i-1,j+1] = 1   
                    CCtmp[i+1,j-1] = 1   
    CC = CC + CCtmp
    nn = np.amin(CC)
    MAX_RADIUS += 1
print('Max radius within ' + str(N) + ' is less than ' + str(MAX_RADIUS) + '.\n\n') 
Keeping mind the point of the code: how far away from a one is the farthest zero, any other suggestions are welcome.