我有一个-
字符列表列表,作为网格。
我想将每个列和行-
更改为Q
。
这是我到目前为止所得到的:
import pprint
import random # I import these classes
grid = [['-'] for n in range(8)]
for i in range (8):
for j in range(8):
inserPoint = random.randrange(8,8)
if (j == inserPoint or i == inserPoint) and (grid[j] != 'Q' or grid[i] != 'Q'):
grid[i][j] = ('Q')
pprint.pprint(grid) #/ how to print one queen per line
这是我的输出。正如您所看到的,网格上有Q
个太多:
[['-','-','-','-','-','-','Q','-'],
['-','-','-','-','Q','Q','-','-']
['-','-','-','-','Q','-','-','-']
['Q','Q','-','-','-','Q','Q','-']
['-','-','Q','-','Q','-','-','-'].
答案 0 :(得分:3)
一些事情:
i
,然后只需插入Q
告诉您的randrange
。randrange
来电错误。它应该有一个开始和一个停止。事实上,如果您希望rangerange
在行和列中唯一,Q
不是正确的工具。以下是所有三件事:
In [34]: size = 8
In [35]: grid = [['-' for m in range(size)] for n in range(size)]
In [36]: insertPoints = range(size) # = list(range(size)) in Python 3
In [37]: random.shuffle(insertPoints)
In [38]: for i in range(size):
....: grid[i][insertPoints[i]] = "Q"
给出了:
In [39]: grid
Out[39]:
[['-', '-', '-', 'Q', '-', '-', '-', '-'],
['-', 'Q', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', 'Q', '-'],
['-', '-', '-', '-', '-', 'Q', '-', '-'],
['Q', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', 'Q', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', 'Q'],
['-', '-', 'Q', '-', '-', '-', '-', '-']]
(请参阅this了解为什么改组范围在Python 3中不起作用)