27
27
@author: John Svazic
28
28
"""
29
29
30
- from random import (random , randint )
30
+ from random import (choice , random , randint )
31
31
32
32
__all__ = ['Chromosome' , 'Population' ]
33
33
34
- class Chromosome ( object ) :
34
+ class Chromosome :
35
35
"""
36
36
This class is used to define a chromosome for the gentic algorithm
37
37
simulation.
@@ -57,8 +57,8 @@ def mate(self, mate):
57
57
resulting in a new chromosome being returned.
58
58
"""
59
59
pivot = randint (0 , len (self .gene ) - 1 )
60
- gene1 = self .gene [0 :pivot ] + mate .gene [pivot :]
61
- gene2 = mate .gene [0 :pivot ] + self .gene [pivot :]
60
+ gene1 = self .gene [:pivot ] + mate .gene [pivot :]
61
+ gene2 = mate .gene [:pivot ] + self .gene [pivot :]
62
62
63
63
return Chromosome (gene1 ), Chromosome (gene2 )
64
64
@@ -69,7 +69,7 @@ def mutate(self):
69
69
will be created, but this original will not be affected.
70
70
"""
71
71
gene = list (self .gene )
72
- delta = randint (0 , 89 ) + 32
72
+ delta = randint (32 , 121 )
73
73
idx = randint (0 , len (gene ) - 1 )
74
74
gene [idx ] = chr ((ord (gene [idx ]) + delta ) % 122 )
75
75
@@ -95,11 +95,11 @@ def gen_random():
95
95
"""
96
96
gene = []
97
97
for x in range (len (Chromosome ._target_gene )):
98
- gene .append (chr (randint (0 , 89 ) + 32 ))
98
+ gene .append (chr (randint (32 , 121 ) ))
99
99
100
100
return Chromosome ('' .join (gene ))
101
101
102
- class Population ( object ) :
102
+ class Population :
103
103
"""
104
104
A class representing a population for a genetic algorithm simulation.
105
105
@@ -128,9 +128,9 @@ def _tournament_selection(self):
128
128
A helper method used to select a random chromosome from the
129
129
population using a tournament selection algorithm.
130
130
"""
131
- best = self . population [ randint ( 0 , len ( self .population ) - 1 )]
131
+ best = choice ( self .population )
132
132
for i in range (Population ._tournamentSize ):
133
- cont = self . population [ randint ( 0 , len ( self .population ) - 1 )]
133
+ cont = choice ( self .population )
134
134
if (cont .fitness < best .fitness ): best = cont
135
135
136
136
return best
@@ -149,7 +149,7 @@ def evolve(self):
149
149
"""
150
150
size = len (self .population )
151
151
idx = int (round (size * self .elitism ))
152
- buf = self .population [0 :idx ]
152
+ buf = self .population [:idx ]
153
153
154
154
while (idx < size ):
155
155
if random () <= self .crossover :
@@ -168,7 +168,7 @@ def evolve(self):
168
168
buf .append (self .population [idx ])
169
169
idx += 1
170
170
171
- self .population = list (sorted (buf [0 :size ], key = lambda x : x .fitness ))
171
+ self .population = list (sorted (buf [:size ], key = lambda x : x .fitness ))
172
172
173
173
if __name__ == "__main__" :
174
174
maxGenerations = 16384
0 commit comments