3/19 Board is weird


#1
   board = []

    for x in range(0, 5):
         board.append(["O"] * 5)
    
print board

Creates a board like this

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

when i need a board like this

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

How do I make it use a new line? In CPP its just endl; , So im looking for an equivalent


#2

To print the board out you will need to make code to print it out like that, the way it is displaying it is the way that python stores the data.

def print_board(board_item):
    for row in board_item:
        print(' '.join(row))

print_board(board)

#3

board = ["O"]*5

def new_board(x):
for i in range(0, len(x)):
board.append(x*5)

print new_board(board)

Salva252, when you have a moment I would like to understand how you arrived at your code. Its obvious that I made my code to complicated.

I messed up and I don't know how I did it. When I tried your code, of course it was flawless. I just need to trade on simplifying ideas for coding when you have a chance. Thanks.


#4

@armbarznkimuraz

Your code should throw an error correct?

In python a string object is immutable so also it does not have a string method called append.

Append belongs to lists exclusively.

You can use just simple list comprehension(aka generators) to create the board or you can use for loops.

Below I have several ways you can accomplish what you seek, try them all and see what happens.

Also as a note each one is accessed the same exact way even though some of them the information is stored slightly different.

EXAMPLE: Of Access

board[0][0]
board[4][4]

EXAMPLE CODE:

board = [["O" *5] for i in range(5)]

OR

board = [["O" for i in range(5)] for j in range(5)]

OR

board = []
for i in range(5):
    board.append("O" * 5)

OR

board_item = "O"
board = []
for i in range(5):
    board += board_item * 5

OR

board_item = "O"
board = []
for i in range(5):
    board.append([board_item * 5])

#5

5/19 will cover this. As long as your code is valid just move on to the next section and all will be clear!


#6

Covered in 5/19. Try this code out:

board = []

for i in range(5):
row = []
board.append(row)
for j in range (5):
row.append("O")

def print_board(board):
for row in range (len(board)):
print board[row]

print_board(board)