Count string elements on a map based on where strings are and fill grid with the counts
14:48 02 Jan 2019

I have a list called my_map that contains two different kinds of string values '.' and '&'. Now, for each value [x][y] that is a '.' I want to count the number of times an '&' was found in any of the eight directions next to the '.'

I created a grid to store the counts but I am just not able to formulate my conditions correctly. I can not use numpy arrays.

Note: 'S' and 'E' are treated like '.'

 my_map = ['................' '....&...........' '..........E.....'
 '&&..&...........' '....&&&.........' '......&&&&..&&..'
 '................' '.......&........' '.....&.&........'
 '....S...........' '.......&.&&.....']

def create_grid(my_map):
    grid = [[0]*(len(my_map[0])) for x in range(len(my_map))]
    return grid

grid = create_grid(my_map)

for x, y in [(x,y) for x in range(len(my_map)) for y in range(len(my_map[0]))]:
    #any '&' north ?
    if my_map[x][y+1]== '&' and my_map[x][y]=='.': 
        grid[x][y]+= 1
        #any '&' west ?
        if my_map[x-1][y]== '&' and my_map[x][y]=='.': 
            grid[x][y]+=1
            #any '&' south ?
            if my_map[x][y-1]== '&'and my_map[x][y]=='.': 
                grid[x][y]+=1
                #any '&' east ?
                if my_map[x+1][y]== '&'and my_map[x][y]=='.': 
                    grid[x][y]+=1
                    #any '&' north-east ?
                    if my_map[x+1][y+1] == '&'and my_map[x][y]=='.': 
                        grid[x][y]+=1
                        #any '&' south-west ?
                        if my_map[x-1][y-1] == '&'and my_map[x][y]=='.': 
                            grid[x][y]+=1
                            #any '&' south-east ?
                            if my_map[x+1][y-1]== '&'and my_map[x][y]=='.': 
                                grid[x][y]+=1
                                #any '&' north-west?
                                if my_map[x-1][y+1]== '&'and my_map[x][y]=='.': 
                                    grid[x][y]+=1

 #desired output for first 3 rows
grid = [[0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0],[2,2,1,1,2,1,0,0,0,0,0,0,0,0,0,0]]

At the moment, I get an 'IndexError: string index out of range'. I dont know how to limit the range so it will still be correct.The only thing I managed so far was a grid displaying 1s for all '.' and 0s for all '&'.

python list conditional-statements counting directions