def countNeighbours(grid, x, y):
    """
    Counts the neighbours around the given cell.
    If the cell is on the edge, only the neighbours on the grid will be counted.
    """
    count = 0
    for dx in range(x-1, (x+1)+1):
        dx %= grid.shape[0] #To connect edges instead of clipping

        for dy in range(y-1, (y+1)+1):
            dy %= grid.shape[1] #To connect top and bottom
            if dx == x and dy == y: continue

            count += grid[dy][dx]
    return count