我正在尝试完成一些学校作业的问题,但我遇到了人类有史以来最糟糕的脑放屁情况。这个问题要求三件事。
• 它单独读取一行中的数字N。这将是拉丁方的顺序。该订单必须是 正整数,例如 N > 0。
• 它读取 N 行 N 个数字,即读取一个数字平方的控制台输入。
• 检查数字序列是否是拉丁方阵。你的程序应该显示 如果满足上述条件,则消息"is",如果不满足,则消息“否”。
我当前的代码是这样的:
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
这不需要制作一个正方形,但它确实帮助我更好地可视化它。
所以我的主要问题是,有没有一种好方法可以让用户输入的拉丁方变成实际的拉丁方?
要注意的是,我不是在寻找任何答案,我只是想要一些帮助来克服我的心理障碍。
最佳答案
我明白了,抱歉打扰你们了!答案是这样的
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())
关于python-3.x - 制作拉丁方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48343134/