code kid -4 years ago 125
Python Question

# Switch operands in loops Python 3

I want to be able to switch operands each time through a loop. So the first time through I'd like to add column. The second time through the loop I'd like to subtract from column. The third time through I would like to subtract from column and subtract from row. The fourth time through I'd like to subtract from column and add to row. Is this possible to write one loop to accomplish this instead of several? Thanks for the help!

``````#add
for x in range(1,8):
if game[column+x][row] == 'W':
game[column+x][row] = 'B'
elif game[column+x][row] == 'B':
return
#subtract
for x in range(1,8):
if game[column-x][row] == 'W':
game[column-x][row] = 'B'
elif game[column-x][row] == 'B':
return
#etc....
for x in range(1,8):
if game[column-x][row-x] == 'W':
game[column-x][row-x] = 'B'
elif game[column-x][row-x] == 'B':
return

for x in range(1,8):
if game[column-x][row+x] == 'W':
game[column-x][row+x] = 'B'
elif game[column-x][row+x] == 'B':
return
``````

By your code I'm assuming you want to mark each 'W' surrounding cell with 'B'. This should be enough:

``````neighbours = [
(-1, -1),
(-1,  0),
(-1,  1),
( 0, -1),
( 0,  0),
( 0,  1),
( 1, -1),
( 1,  0),
( 1,  1)
]

game = [
['W', 'W', 'E'],
['' ,  '',  ''],
['' ,  '',  '']
]

print game

row, col = 1, 1 # center of the game's table

for x, y in neighbours:
if game[row + x][col + y] == 'W':
game[row + x][col + y] = 'B'

print game
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download