【发布时间】:2017-08-21 16:46:55
【问题描述】:
我试图用随机整数 1-4 在 python 中编写一个 4x4 矩阵。 这很简单,我的问题是我希望每一行和每一列只使用一次每个数字 1-4
例子
1 2 3 4
2 3 4 1
3 4 1 2
4 1 2 3
我的代码在我的循环中有 33% 的时间会发生这样的事情
2 1 4 3
3 4 2 1
1 3 X
""" Programm for playing the game skyline """
from random import randrange
row1 = []
row2 = []
row3 = []
row4 = []
allrows = [row1, row2, row3, row4]
column1 = []
column2 = []
column3 = []
column4 = []
allcolumns = [column1, column2, column3, column4]
def board():
for i in range(4):
j = 0
while len(allrows[i]) != 4:
x = randrange(1,5)
print(i, j)
if x not in allrows[i] and x not in allcolumns[j]:
allrows[i].append(x)
allcolumns[j].append(x)
j += 1
else:
continue
board()
【问题讨论】:
标签: python python-3.x matrix infinite-loop