Frage

s = [0,2,6,4,7,1,5,3]


def row_top():
    print("|--|--|--|--|--|--|--|--|")

def cell_left():
   print("| ", end = "")

def solution(s):
   for i in range(8):
       row(s[i])

def cell_data(isQ):
   if isQ:
      print("X", end = "")
      return ()
   else:
      print(" ", end = "")


def row_data(c):
   for i in range(9):
      cell_left()
      cell_data(i == c)

def row(c):
   row_top()
   row_data(c)
   print("\n")


solution(s)

My output has a space every two lines, when there shouldn't be, I'm not sure where it's creating that extra line.

The output is suppose to look like this:

|--|--|--|--|--|--|--|--|
|  |  |  |  |  | X|  |  |
|--|--|--|--|--|--|--|--|
|  |  | X|  |  |  |  |  |
|--|--|--|--|--|--|--|--|
|  |  |  |  | X|  |  |  | 
|--|--|--|--|--|--|--|--|
|  |  |  |  |  |  |  | X|
|--|--|--|--|--|--|--|--|
| X|  |  |  |  |  |  |  |
|--|--|--|--|--|--|--|--|
|  |  |  | X|  |  |  |  |
|--|--|--|--|--|--|--|--|
|  | X|  |  |  |  |  |  |
|--|--|--|--|--|--|--|--|
|  |  |  |  |  |  | X|  |
|--|--|--|--|--|--|--|--|

I know this chess board isn't very square but this is only a rough draft at the moment.

War es hilfreich?

Lösung 2

You are still printing an extra newline:

def row(c):
   row_top()
   row_data(c)
   print("\n")

Remove the explicit ''\n'` character:

def row(c):
    row_top()
    row_data(c)
    print()

or better still, follow my previous answer more closely and print a closing | bar:

def row(c):
    row_top()
    row_data(c)
    print('|')

Andere Tipps

Here is an alternative implementation:

def make_row(rowdata, col, empty, full):
    items = [col] * (2*len(rowdata) + 1)
    items[1::2] = (full if d else empty for d in rowdata)
    return ''.join(items)

def make_board(queens, col="|", row="---", empty="   ", full=" X "):
    size = len(queens)
    bar = make_row(queens, col, row, row)
    board = [bar] * (2*size + 1)
    board[1::2] = (make_row([i==q for i in range(size)], col, empty, full) for q in queens)
    return '\n'.join(board)

queens = [0,2,6,4,7,1,5,3]
print(make_board(queens))

which results in

|---|---|---|---|---|---|---|---|
| X |   |   |   |   |   |   |   |
|---|---|---|---|---|---|---|---|
|   |   | X |   |   |   |   |   |
|---|---|---|---|---|---|---|---|
|   |   |   |   |   |   | X |   |
|---|---|---|---|---|---|---|---|
|   |   |   |   | X |   |   |   |
|---|---|---|---|---|---|---|---|
|   |   |   |   |   |   |   | X |
|---|---|---|---|---|---|---|---|
|   | X |   |   |   |   |   |   |
|---|---|---|---|---|---|---|---|
|   |   |   |   |   | X |   |   |
|---|---|---|---|---|---|---|---|
|   |   |   | X |   |   |   |   |
|---|---|---|---|---|---|---|---|

It is now very easy to change the width of the board by changing the strings passed to row, empty, full; I added an extra char to each, resulting in a (somewhat) squarer board.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top