-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmagic_square.py
More file actions
50 lines (44 loc) · 1.14 KB
/
magic_square.py
File metadata and controls
50 lines (44 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def formingMagicSquare(s, m_sqs):
s = s[0] + s[1] + s[2]
min_cost = 0
for i in m_sqs:
m_arr = i[0] + i[1] + i[2]
cost = 0
for i, j in zip(s, m_arr):
cost += abs(i - j)
if cost == 0:
return 0
if min_cost == 0:
min_cost = cost
if cost < min_cost:
min_cost = cost
return min_cost
def generate():
sq = [[0] * 3 for _ in range(3)]
r = 1
i = 2
for num in range(1, 10):
sq[r][i] = num
if num % 3 == 0:
i -= 1
else:
r -= 1
i += 1
r = r % 3
i = i % 3
rotate = [[i for i in sq],
[i for i in sq[::-1]],
[i[::-1] for i in sq],
[i[::-1] for i in sq[::-1]]]
mirror = []
for arr in rotate:
a = [i[0] for i in arr]
b = [i[1] for i in arr]
c = [i[2] for i in arr]
mirror.append([a, b, c])
return rotate + mirror
if __name__ == '__main__':
s = []
for _ in range(3):
s.append(list(map(int, input().rstrip().split())))
result = formingMagicSquare(s, generate())