简体   繁体   中英

Python: check whether a square is a heterosquare

My Python book has an exercise that says to define a function that returns true if a square is a heterosquare. There is no answer in the back, but I started working on it thinking it was a common problem that would have many solutions on this site, but I can't find any.

I've pasted my code for where I have gotten up to so far. I'm thrown off by the checking diagonals part and I'm not sure what to do. Could anyone please help me solve it a simple beginner's way without a complex solution?

Here is the problem definition: A heterosquare is an n×n array of the integers from 1 to n^2 such that the rows, columns, and diagonals have different sums.

def isHeterosquare(square):
    n = len(square)
    sum = n * (n ** 2 + 1) // 2
    if any(len(line) != n for line in square):
        return False
    if {num for line in square for num in line} != set(range(1, n ** 2 + 1)):
        return False

    # check if each element in the square sums the same for each row, column and diagonal:
    [square[i][j] for i in range(n)] for j in range(n)]


    return True

This is an example of how the function should be called, so that it returns true.

isHeterosquare([[1, 2, 3, 4],\
                     [5, 6, 7, 8],\
                     [9, 10, 11, 12],\
                     [13, 14, 16, 15]])
True

Edit: An example of False is this one below because you can see that the rows all sum to 15, the columns all sum to 15, and the diagonal from 2,5,8 sums to 15. So this one will return False since a heterosquare would have different sums on the diagonals, columns and rows.

isHeterosquare([[2,7,6],\
                     [9,5,1],\
                     [4,3,8]])
False

Here is what I would do: find the sum of all rows, columns and diagonals and store in a list. If all sums are unique, then length of list and length of set of that list will be same. See if this helps.

def get_sum_row(mat, row):
    return sum(mat[row])

def get_sum_col(mat, col):
    return sum(mat[i][col] for i in range(len(mat)))

def get_sum_dias(mat):
    n = len(mat)
    sum_dia1 = sum(mat[i][i] for i in range(n))
    sum_dia2 = sum(mat[i][n-i-1] for i in range(n))

    return [sum_dia1, sum_dia2]

def is_hetero_square(mat):
    sum_l = list()

    for i in range(len(mat)):
        sum_l.append(get_sum_row(mat, i))
        sum_l.append(get_sum_col(mat, i))

    sum_l.extend(get_sum_dias(mat))

    return len(sum_l) == len(set(sum_l))

mat1 = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,16,15]]
print(is_hetero_square(mat1)) # Prints True

mat2 = [[1,2,3],[4,5,6],[7,8,9]]
print(is_hetero_square(mat2)) # Prints False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM