Python 中的 4x4 矩阵

4x4 Matrix in Python

我正在尝试使用随机整数 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()

基本上,您所做的就是将您想要 select 的号码放入列表中。随机选择一个索引,使用和删除它。 下一次,你选择剩下的一个。

您似乎在寻找排列组合,以下是获取排列组合的方法:

from itertools import permutations
a = list(permutations([1,2,3,4]))

现在随机获取 4 个列表:

import random

from itertools import permutations
a = list(permutations([1,2,3,4]))

for _ in range(4):
    print a[random.randint(0,len(a)-1)]

编辑 这就是你要找的那个吗:

import random
import numpy as np

from itertools import permutations
a = list(permutations([1,2,3,4]))

i = 0
result = [a[random.randint(0,len(a)-1)]]
a.remove(result[0])
print result
while i < 3:
     b = a[random.randint(0,len(a)-1)]
     if not any([any(np.equal(b,x)) for x in result]):
         result.append(b)
         i +=1
     a.remove(b)

print result

我已经尝试过使用 for、if 和 elif;对于大于 4 的范围,它正在工作。

x=int(input("enter your range"))
for i in range(x+1):
if i+1<x+1:
print(i+1,end='')
if(i+2<x+1):
   print(i+2,end='')
   if(i+3<x+1):
    print(i+3,end='')
    if(i+4<x+1):
     print(i+4)
    elif(i!=0 and i+4>=x+1):
      print(i)
   elif(i!=0 and i+3>=x+1):
    print(i-1,end='')
    print(i)
elif(i!=0 and i+2>=x+1):
  print(i-2,end='')
  print(i-1,end='')
  print(i)