2

我试图为一些学校作业完成一个问题,而我只是遇到了人类见过的最糟糕的脑放屁情况。这个问题要求三件事。

• 它自己读取一行上的数字N。这将是一个拉丁正方形的顺序。顺序必须是正整数,例如 N > 0。

• 它读取N 行N 的数字,即,它读取控制台输入的正方形数字。

• 它检查数字序列是否是拉丁方格。如果您的程序满足上述标准,则应显示消息“是”,否则应显示“否”。

我目前的代码是这样的:

def makelatin():

order = int(input("Enter the order of the latin square: "))

latin = [int(x) for x in input("enter the latin square with spaces inbetween the numbers: ").split()]




def checklatin(latin) :

    numbers = set(range(1, len(latin) + 1))

    if (any(set(row) != numbers for row in latin) or any(set(col) != numbers for col in zip(*latin))) :

        print ("False")

    print ("True")

checklatin(a) 

所以我想到的是,做一个拉丁方块,然后检查它。我的问题是,我目前停留在 makelatin 部分。用户输入拉丁方格的顺序,然后他们在输入中输入方格。

例子:

"enter order of square" = 3

"enter the square" = 3 2 1 1 3 2 2 1 3 

哪个会做一个像这样的拉丁方

3 2 1 

1 3 2 

2 1 3 

这不需要制作一个正方形,但它确实帮助我更好地想象它。

所以我的主要问题是,有没有一种好方法可以让用户将拉丁方输入到实际的拉丁方中?

需要注意的是,我不是在寻找任何答案,我只是想要一些帮助来克服我的心理障碍。

4

2 回答 2

2

明白了,不好意思打扰各位了!答案是这个

def makelatin():

    order = int(input("Enter the order of the latin square: "))
    latin = [int(x) for x in input("enter the latin square with spaces inbetween the numbers: ").split()]

    return (list(zip(*(iter(latin),) * order)))


def checklatin(latin) :
    numbers = set(range(1, len(latin) + 1))
    if (any(set(row) != numbers for row in latin) or any(set(col) != numbers for col in zip(*latin))) :
        print ("False")
    else:
        print ("True")

#a = [[1, 2, 3, 4, 5],
     [2, 3, 5, 1, 4],
     [3, 5, 4, 2, 1],
     [4, 1, 2, 5, 3],
     [5, 4, 1, 3, 2]]


checklatin(makelatin())
于 2018-01-19T14:46:34.200 回答
0

如果你不介意我使用 matlab:

n=5;
% create an empty matrix of NaNs.
latinSquare=nan(n);
% fill the 1st column.
latinSquare(:,1)=1:n;

% define a variable of how we want to shift the 1s column to fill the remaining columns.
% ballanced order:
shiftsize=(.5-mod(1:n-1,2))/.5.*ceil((1:n-1)/2);
% normal order:
%shiftsize=n-1:-1:1;


for col=2:n
    latinSquare(:,col)=circshift((1:n)',shiftsize(col-1));
end

这将是平衡拉丁方格的输出:

ans =

 1     2     5     3     4
 2     3     1     4     5
 3     4     2     5     1
 4     5     3     1     2
 5     1     4     2     3

这是普通的拉丁方格:

ans =

 1     2     3     4     5
 2     3     4     5     1
 3     4     5     1     2
 4     5     1     2     3
 5     1     2     3     4

现在我用python重写它:

def latin_square(n, mod='ballanced'):

  import numpy as np

  mat = np.empty((n,n,))*np.nan

  mat[:,0] = range(1,n+1)

  if mod=='ballanced':
    shift = (.5-np.mod(np.array(range(1,n)),2))/.5*np.ceil(np.array(range(1,n))/2)
    shift = shift.astype(int)
  elif mod=='normal':
    shift = np.array(range(n-1, -1, -1))

  for col in range(1, n):
    mat[:, col] = np.roll(mat[:,0], shift[col-1])
    
  return(mat)
    

latin_square(6)

array([[1., 2., 6., 3., 5., 4.],
   [2., 3., 1., 4., 6., 5.],
   [3., 4., 2., 5., 1., 6.],
   [4., 5., 3., 6., 2., 1.],
   [5., 6., 4., 1., 3., 2.],
   [6., 1., 5., 2., 4., 3.]])
于 2020-09-13T01:41:18.977 回答