-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathexercise (6).py
85 lines (61 loc) · 1.94 KB
/
exercise (6).py
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
from random import randint
from unittest import TestCase
class Generator:
def generate(self, count):
return [randint(1, 9) for x in range(count)]
class Splitter:
def split(self, array):
result = []
row_count = len(array)
col_count = len(array[0])
for r in range(row_count):
the_row = []
for c in range(col_count):
the_row.append(array[r][c])
result.append(the_row)
for c in range(col_count):
the_col = []
for r in range(row_count):
the_col.append(array[r][c])
result.append(the_col)
diag1 = []
diag2 = []
for c in range(col_count):
for r in range(row_count):
if c == r:
diag1.append(array[r][c])
r2 = row_count - r - 1
if c == r2:
diag2.append(array[r][c])
result.append(diag1)
result.append(diag2)
return result
class Verifier:
def verify(self, arrays):
first = sum(arrays[0])
for i in range(1, len(arrays)):
if sum(arrays[i]) != first:
return False
return True
class MagicSquareGenerator:
def generate(self, size):
g = Generator()
s = Splitter()
v = Verifier()
while True:
square = []
for x in range(size):
square.append(g.generate(size))
if v.verify(s.split(square)):
break
return square
class Evaluate(TestCase):
def test_exercise(self):
gen = MagicSquareGenerator()
square = gen.generate(3)
print(square)
v = Verifier()
self.assertTrue(
v.verify(square),
"Verification failed. " "This is not a valid magic square.",
)