【问题标题】:4x4 Matrix in PythonPython中的4x4矩阵
【发布时间】: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


    【解决方案1】:

    基本上,您所做的就是将要从中选择的数字放在一个列表中。随机选择一个索引,使用和删除它。 下一次,你选择剩下的一个。

    【讨论】:

    • 我已经拿到了那个部分,现在的问题是我可以到达一个无法继续的部分。
    • @justhechi,这个。您应该对每个数字递归地执行此操作。如果在某一时刻列表变为空,您应该返回前一个数字并尝试另一个数字。抱歉,我知道这听起来有点令人困惑(我现在很困,我很难写出正确、全面的答案),但您可能想阅读一些关于回溯的内容。 This Wikipedia 文章可能是一个不错的起点。
    【解决方案2】:

    你似乎在寻找排列,这里是如何得到它们:

    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)]
    

    EDIT这是您要找的那个吗:

    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
    

    【讨论】:

    • 谢谢,但我已经有了那部分,重要的是列没有相同的数字(有点像数独)
    【解决方案3】:

    我已经尝试过使用 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)
    

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 2010-11-12
      • 2014-11-13
      • 1970-01-01
      • 2021-03-19
      • 2016-04-22
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      相关资源
      最近更新 更多