@@ -96,16 +96,21 @@ def test_genetic_algorithm():
96
96
'D' : [2 , 3 ]
97
97
}
98
98
99
- population = init_population (8 , ['0' , '1' ], 4 )
100
-
101
99
def fitness (c ):
102
100
return sum (c [n1 ] != c [n2 ] for (n1 , n2 ) in edges .values ())
103
101
104
- solution = genetic_algorithm (population , fitness )
105
- assert solution == "0101" or solution == "1010"
102
+ solution_chars = GA_GraphColoringChars (edges , fitness )
103
+ assert solution_chars == ['R' , 'G' , 'R' , 'G' ] or solution_chars == ['G' , 'R' , 'G' , 'R' ]
104
+
105
+ solution_bools = GA_GraphColoringBools (edges , fitness )
106
+ assert solution_bools == [True , False , True , False ] or solution_bools == [False , True , False , True ]
107
+
108
+ solution_ints = GA_GraphColoringInts (edges , fitness )
109
+ assert solution_ints == [0 , 1 , 0 , 1 ] or solution_ints == [1 , 0 , 1 , 0 ]
106
110
107
111
# Queens Problem
108
- population = init_population (100 , [str (i ) for i in range (8 )], 8 )
112
+ gene_pool = range (8 )
113
+ population = init_population (100 , gene_pool , 8 )
109
114
110
115
def fitness (q ):
111
116
non_attacking = 0
@@ -122,10 +127,31 @@ def fitness(q):
122
127
return non_attacking
123
128
124
129
125
- solution = genetic_algorithm (population , fitness , f_thres = 25 )
130
+ solution = genetic_algorithm (population , fitness , gene_pool = gene_pool , f_thres = 25 )
126
131
assert fitness (solution ) >= 25
127
132
128
133
134
+ def GA_GraphColoringChars (edges , fitness ):
135
+ gene_pool = ['R' , 'G' ]
136
+ population = init_population (8 , gene_pool , 4 )
137
+
138
+ return genetic_algorithm (population , fitness , gene_pool = gene_pool )
139
+
140
+
141
+ def GA_GraphColoringBools (edges , fitness ):
142
+ gene_pool = [True , False ]
143
+ population = init_population (8 , gene_pool , 4 )
144
+
145
+ return genetic_algorithm (population , fitness , gene_pool = gene_pool )
146
+
147
+
148
+ def GA_GraphColoringInts (edges , fitness ):
149
+ population = init_population (8 , [0 , 1 ], 4 )
150
+
151
+ return genetic_algorithm (population , fitness )
152
+
153
+
154
+
129
155
# TODO: for .ipynb:
130
156
"""
131
157
>>> compare_graph_searchers()
0 commit comments