Python 为8皇后拼图创建一个棋盘
我的输出每两行有一个空格,当不应该有空格时,我不确定它在哪里创建了额外的行 假设输出如下所示:Python 为8皇后拼图创建一个棋盘,python,function,for-loop,ascii,ascii-art,Python,Function,For Loop,Ascii,Ascii Art,我的输出每两行有一个空格,当不应该有空格时,我不确定它在哪里创建了额外的行 假设输出如下所示: 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):
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)
我知道这个棋盘不是很方,但目前这只是一个草稿。您仍在打印一个额外的换行符:
|--|--|--|--|--|--|--|--|
| | | | | | X| | |
|--|--|--|--|--|--|--|--|
| | | X| | | | | |
|--|--|--|--|--|--|--|--|
| | | | | X| | | |
|--|--|--|--|--|--|--|--|
| | | | | | | | X|
|--|--|--|--|--|--|--|--|
| X| | | | | | | |
|--|--|--|--|--|--|--|--|
| | | | X| | | | |
|--|--|--|--|--|--|--|--|
| | X| | | | | | |
|--|--|--|--|--|--|--|--|
| | | | | | | X| |
|--|--|--|--|--|--|--|--|
删除显式“\n”字符:
def row(c):
row_top()
row_data(c)
print("\n")
或者更好的做法是,更仔细地按照我之前的答案,打印一个结束语|
栏:
def row(c):
row_top()
row_data(c)
print()
下面是一个替代实现:
def row(c):
row_top()
row_data(c)
print('|')
导致
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))
现在,通过改变传递到row、empty、full的字符串,可以很容易地改变电路板的宽度;我在每个面板上添加了一个额外的字符,从而形成了一个(稍微)方形的面板。?相同?请阅读关于这一点的评论…好的,但请不要为每一个小的变化问单独的问题。最好只问一次。@pakiboii如果在另一个问题上你没有编辑这个问题来包含答案,这个问题就不会像那个问题。这就是为什么我试图回滚你在那里做的编辑。我这么做了,但其他人让我做一个单独的问题,这就是我所做的。
|---|---|---|---|---|---|---|---|
| X | | | | | | | |
|---|---|---|---|---|---|---|---|
| | | X | | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | X | |
|---|---|---|---|---|---|---|---|
| | | | | X | | | |
|---|---|---|---|---|---|---|---|
| | | | | | | | X |
|---|---|---|---|---|---|---|---|
| | X | | | | | | |
|---|---|---|---|---|---|---|---|
| | | | | | X | | |
|---|---|---|---|---|---|---|---|
| | | | X | | | | |
|---|---|---|---|---|---|---|---|