Search code examples
for-looppython-3.xnested-loopsnested-lists

Noughts and Crosses loops


iv'e been working on this question, and i think im nearly there.

Question:

Write a function get_column(game, col_num) that takes a legal 3 x 3 game of noughts and crosses and returns a 3-element list containing the values from column number col_num, top to bottom. You may assume col_num is in the range 0 to 2 inclusive. [Hint: you will have to build the return value by looping over the rows, picking out the required element of each row.]

My working:

def get_column(game, col_num):
    x = []
    for i in game:
        for j in i:
            x.append(i[col_num])
    return x

Testing:

column1 = get_column([['O', 'X', 'O'], ['X', ' ', ' '], [' ', ' ', ' ']], 0)

print(column1)

Results:

['O', 'O', 'O', 'X', 'X', 'X', ' ', ' ', ' ']

Wanted format:

['O', 'X', ' '].

I'm pretty sure i'm getting the correct answer, however, not in the right format. the results are showing that im increasing the 'O'/'X' two more time. i guess this has something to do with the loops, but i can detect what exactly.

any help would be appreciated! Cheers!


Solution

  • def get_column(game, col_num):
        x = []
        for i in range(3):
            x.append(game[i][col_num])
        return x