Ted Ted - 1 year ago 71
Python Question

How can I alter this for-loop to alternate between 2 different characters as it inserts values, instead of only one value?

I am trying to construct the game Konane (this link provides the game rules if you need to refer to them to better understand my question). I have created the function that will build the empty array, however am unclear as to what the best way is to go about filling the grid with alternating

values. One important rule pertaining to this is that the location cannot have the same value above, below, left, or right of itself.

Here is my current function that creates the empty array that I would like to alter to perform the above tasks:

numrows = 3
numcols = 4
def empty_grid():
return [['-' for y in range(numcols)]
for x in range(numrows)]

Answer Source

This is how I would implement the array initialization in the way that you want, and then print it to verify. There are other ways to accomplish the alternation you are looking for; taking the the sum of the indices modulo 2 is the most logical to me.

area = empty_grid()            # get an empty_grid called area

for i in range(numrows):       # go through the rows
    for j in range(numcols):   # go through the columns
        if (i + j) % 2:        # add the indices and check for oddness
            area[i][j] = 'B'   # if odd, set to B
            area[i][j] = 'W'   # else (if even), set to W

for i in range(numrows):       # for each row
    print area[i]              # print the row


['W', 'B', 'W', 'B']
['B', 'W', 'B', 'W']
['W', 'B', 'W', 'B']

The trickiest part is figuring out how to alternate on each row and offset each row so they are staggered by one. You can do this by using a counter variable (like k) and adding one to it each time, although I would still end up checking evenness/oddness of something, so I found adding the indices to be the simplest for me to understand.

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