3/19 - Creating the board


#1

Hi all,

I have a problem creating my battleship board. My code looks as though it's almost right, but it fails... I think because it's a list inside a list?

Could someone explain what's going wrong? Help much appreciated!!

board = []
circles = ["O"] * 5
board.append(circles)

for i in range(0,5):
print board

[['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']]
None


#2

Yea, that is a problem.

It wants,

board = ['OOOOO', 'OOOOO'] #ect

Though functionally your board is no different from that one, both are called in the same exact manner.

It wants you to program something like this

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

The way you are going about it is the better choice though because even strings in lists are technically immutable, so storing your information in something like that is only a good idea if you plan to not work on it.


#3

Hey blogpro42444,

I see a couple things that might be issues. The first a structural issue:

board = []
circles = ["O"] * 5
board.append(circles)

In your code you're building the board by defining an empty list (board = []), which is correct.
Then you're going inserting a single nested list into that list. This last part is the first mistake.

We DO want to append circles, but we want an easy way to to it 5 times. I think you noticed that issue and tried to fix it on the output side. Hence looping the print function of that one embedded list, which is the second issue I could see:

for i in range(0,5):
print board

So, rather than creating a board that's a single embedded list we need to create a board that is 5 embedded lists. That way we can refer to rows and columns later on. You can do that by moving the code you made equal to 'circles' part of the for loop.

You'll want to keep the [] around the "O" just like you have it as well, since that's what gives you the correct formatting AND allows you to address each item in each row.

So, something a bit more like what @zeziba was recommending, but with the square brackets around the "O". I'd also keep the 'range' as you'd defined it though using a fixed format like @zeziba's way of doing would work just fine as well.

The output from this lesson will be messy:

[['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']]

Later lessons walk you through reformatting it with the end result being well formatted.

Hope that helps!


#4

Excellent! Problem solved.

Many thanks to you and @zeziba for answering this in an understandable and in-depth manner!