Latin Square in Python

PythonServer Side ProgrammingProgramming

Suppose we have an N x N matrix of letters matrix, we have to check whether there are exactly N different letters that appear in the matrix and each letter is present exactly once in each row and exactly once in each column.

So, if the input is like

 x y z z x y y z x

Then the output will be True, as there are 3 different letters and each letter is present exactly once in each row and column.

To solve this, we will follow these steps −

• ch:= a set of all elements present in the matrix
• m:= transpose of mat
• for each row i from mat and row j from m, do
• for each c in ch, do
• if c not in i or c not in j, then
• return False
• return True

Let us see the following implementation to get better understanding −

Example

Live Demo

class Solution:
def solve(self, mat):
ch=set(j for i in mat for j in i)
m=zip(*mat)
for i,j in zip(mat,m):
for c in ch:
if c not in i or c not in j:
return False
return True
ob = Solution()
mat = [["x", "y", "z"],["z", "x", "y"],
["y", "z", "x"]]
print(ob.solve(mat))

Input

[["x", "y", "z"],
["z", "x", "y"],
["y", "z", "x"]]

Output

True
Published on 23-Sep-2020 11:05:26