Reputation: 51
I have a list 'map' and I want to replace all elements by the respectives output values of a function "counterPosition" that acts on each position of the initial array, something like that:
map[0][0] = counterPosition(0,0)
map[0][1] = counterPosition(0,1)
...
Doing one by one like that I can get the answer, but when I try something like that:
for x in range (len(map)):
for y in range (len(map)):
map[x][y] = counterPosition(x,y)
It doesn't work... Am I doing something wrong?
EDIT:
def counterPosition(x, y):
bombs = 0
for i in range(x-1, x+2):
for j in range(y-1, y+2):
if i<0 or j<0: continue
elif map[i][j] == True:
bombs += 1
return bombs
map = [[True, False, False, False, False, True],
[False, False, False, False, False, True],
[True, True, False, True, False, True],
[True, False, False, False, False, False],
[False, False, True, False, False, False],
[False, False, False, False, False, False]]
The error is:
IndexError: list index out of range
Upvotes: 0
Views: 332
Reputation: 32521
You were nearly there
for x in range (len(map)):
for y in range(len(map[x])):
map[x][y] = counterPosition(x,y)
Update: The original code you gave will only run as long as your map is square, but this is the case for the data you provided. Looking at your sample data and updated code, the actual error is coming from your counterPosition
function. Actually there are two problems.
1. In your counterPosition
function you accessing elements that are out of range. This is printed as part of the error message right above IndexError:...
- it's a good idea to read these messages carefully and include it in your post. If you pass in x=5,y-5
then the function will try and access map[6][6]
. The "correct" code should be something like
def counterPosition(x, y):
bombs = 0
for i in range(x-1, x+2):
for j in range(y-1, y+2):
# check bounds:
if 0 <= i < len(map) and 0 <= j < len(map[i]):
if map[i][j] == True:
bombs += 1
return bombs
2. The second problem is that counterPosition
expects map
to contain boolean elements, however you are returning an integer from counterPosition
and assigning that to map[x][y]
. So the next time round map
will contain integer values. Without seeing the rest of your project, I think what you want are two separate multi-dimensional arrays.
Upvotes: 3