Blue Bridge Cup Daily One Question (11): Fill in the blanks (python)

Topic:

The magic square is to fill in some numbers in a square matrix so that the sum of the numbers in the rows, columns, and two diagonals are equal.
The most famous magic square in Europe is a 4th order magic square given in the print "Melancholy" created by German mathematician and painter Diller.
He filled in the 16 numbers 1,2,3,...16 in the 4 x 4 grid.
As shown in the figure, that is:
16?? 13
?? 11?
9?? *
? 15? 1
Some figures in the table have been revealed, and some are replaced by? And *.
Would you please calculate the numbers represented by? And *. And submit the number represented by * as the answer to this question.

Insert picture description here

Solution:

The simplest idea for
filling in the blanks is
to forcefully put the remaining unfilled numbers into nums, arrange all nums, and
then fill them in the array in order.
Calculate the sum of the numbers of rows, columns, and two diagonals
when the output is equal* Value of

Code:

nums = itertools.permutations([2, 3, 4, 5, 6, 7, 8, 10, 12, 14])

for i in nums:
    num = list(i)
    sum_1 = 16 + num[0] + num[1] + 13
    sum_2 = num[2] + num[3] + 11 + num[4]
    sum_3 = 9 + num[5] + num[6] + num[7]
    sum_4 = num[8] + 15 + num[9] + 1
    sum_5 = 16 + num[2] + 9 + num[8]
    sum_6 = num[0] + num[3] + num[5] + 15
    sum_7 = num[1] + 11 + num[6] + num[9]
    sum_8 = 13 + num[4] + num[7] + 1
    sum_9 = 16 + num[3] + num[6] + 1
    sum_10 = 13 + 11 + num[5] + num[8]

    if sum_1 == sum_2 == sum_3 == sum_4 == sum_5 \
            == sum_6 == sum_7 == sum_8 == sum_9 == sum_10:
        print(num[7])
        break

Answer:

12

Guess you like

Origin blog.csdn.net/weixin_50791900/article/details/112756255