Idontreallywolf Idontreallywolf - 1 month ago 9
Python Question

How to first iterate columns and then rows

I am writing a tic tac toe game and I am stuck at the step where code is supposed to check if a player has won VERTICALLY, my friend who knows c++ told me to first iterate thru COLUMNS and then ROWS to make the process easier. Not sure how it works in python.

So for example player enters 4x4 table and after a while this is his result.


[0,1,0,0]
[0,1,0,0]
[0,1,0,0]
[0,1,0,0]


He said that if I iterate thru columns first and then rows then it would be like:

CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0
CHECK,1,0,0


and then column index changes to 1

0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0
0,CHECK,0,0


sorry for bad explanation...

Answer

You can use the built-in all() function to check if all elements are True,
and zip(*table) notation for Row-to-Column Transposition

mytable1 = [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]]
mytable2 = [[0,0,1,0],[0,0,1,0],[0,0,1,0],[0,0,1,0]]
mytable3 = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]
mytable4 = [[0,0,0,1],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable5 = [[0,1,0,0],[0,0,1,0],[0,1,0,0],[1,0,0,0]]
mytable6 = [[2,1,0,0],[2,0,1,0],[2,1,0,0],[2,0,1,0]]
mytable7 = [[2,1,0,0],[0,2,1,0],[0,1,2,0],[0,0,1,2]]

def hasWon(table,player_no):
    #check rows
    for row in table: 
        if all([e==player_no for e in row]):
            return True
    #check columns
    for column in zip(*table): 
        if all([e==player_no for e in column]):
            return True
    #check diagonals
    if all([table[i][i]==player_no for i in range(len(table)) ]): 
        return True
    if all([table[-i-1][i]==player_no for i in range(len(table))]):
        return True
    return False



print(hasWon(mytable1,1))
print(hasWon(mytable2,1))
print(hasWon(mytable3,1))
print(hasWon(mytable4,1))
print(hasWon(mytable5,1))
print(hasWon(mytable6,2))
print(hasWon(mytable7,2))

Outputs:

True
True
True
True
False
True
True