Writing a function that returns boolean true if matrix forms a magic square without importing numpy

后端 未结 1 407
小蘑菇
小蘑菇 2021-01-26 06:26

I already wrote one part of the program which is below:

def matrix_is_square(matrix):
   for i in range(len(matrix)):
      if len(matrix[i]) != len(matrix):
            


        
1条回答
  •  清酒与你
    2021-01-26 07:01

    Complex solution using sum, range, any functions and set object:

    def magic(m):
        length = len(m)
        first_sum = set()
        if length <= 2 \
                or any(len(row) != length for row in m) \
                or any(i > (length * length) for row in m for i in row):
            return False
    
        for r in m:
            s = sum(r)
            if len(first_sum) == 0:
                first_sum.add(sum(r))
            if s not in first_sum:
                return False
    
        for i in range(length):
            s = sum([r[i] for r in m])
            if s not in first_sum:
                return False
    
        if sum(m[i][i] for i in range(length)) not in first_sum \
            or sum(m[i][i] for i in range(length - 1, -1, -1)) not in first_sum:
            return False
    
        return True
    
    m = [[2,7,6],[9,5,1],[4,3,8]]
    print(magic(m))
    
    m = [[16,3,2,13], [5,10,11,8],[9,6,7,12], [4,15,14,1]]
    print(magic(m))
    
    m = [[1,2,3,4], [5,6,7,8],[9,10,11,12], [13,14,15,16]]
    print(magic(m))
    
    m = [[1,1],[1,1]]
    print(magic(m))
    
    m = [[1,1],[1,1],[1,2]]
    print(magic(m))
    

    The output(sequentially):

    True
    True
    False
    False
    False
    

    0 讨论(0)
提交回复
热议问题