6

I'm trying set ships on a Battleship board. The function in the code below should do this with a number of ships and an board (an array of arrays) as arguments. When I run this in Terminal, I get:

[[1, [...]], [1, [...]], [2, [...]]]

What does [...] mean? How to replace [...] with a random integer from 0 to 2 in this output?

from random import randint

def print_board(board):
    for row in board:
        print " ".join(row)
def random_row(board):
    return randint(0, len(board) - 1)
def random_col(board):
    return randint(0, len(board[0]) - 1)

def set_the_ships(num_ships,board):
    ship_list = []
    for i in range(num_ships):
        ship_row = random_row(board)
        ship_col = random_col(board)    
        position = [ship_row,ship_list]
        for j in range(i - 1):
            while (position[0] == ship_list[j][0] and position[1] == ship_list[j][1]):
                ship_row = random_row(board)
                ship_col = random_col(board)    
                position = [ship_row,ship_list]
        ship_list.append(position)
    return ship_list

print set_the_ships(3,[[0,0,0],[0,0,0],[0,0,0]])
justinmoon
  • 443
  • 5
  • 11

2 Answers2

3

... means, there's reference cycle.

>>> l = []
>>> l.append(l)
>>> l
[[...]]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • By "reference cycle" he means that the list contains a reference to itself. – kindall Oct 21 '13 at 14:52
  • 3
    Not only to itself, but to any object already being printed inside the recursive call, consider for example: `a=[]; b=[a]; a.append(b); c=[a]; print c` – lejlot Oct 21 '13 at 14:55
2

See this line:

position = [ship_row,ship_list]

This should be

position = [ship_row,ship_col]

(Same when you re-assign position in thewhile` loop)

Later, when you do ship_list.append(position), this causes ship_list to be nested in itself, which Python prints as [...].

tobias_k
  • 81,265
  • 12
  • 120
  • 179