Skip to content

Commit 12f5a74

Browse files
committed
Minor updates to make the python code a bit cleaner.
1 parent 93add2f commit 12f5a74

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

python/gahelloworld.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,11 @@
2727
@author: John Svazic
2828
"""
2929

30-
from random import (random, randint)
30+
from random import (choice, random, randint)
3131

3232
__all__ = ['Chromosome', 'Population']
3333

34-
class Chromosome(object):
34+
class Chromosome:
3535
"""
3636
This class is used to define a chromosome for the gentic algorithm
3737
simulation.
@@ -57,8 +57,8 @@ def mate(self, mate):
5757
resulting in a new chromosome being returned.
5858
"""
5959
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:]
6262

6363
return Chromosome(gene1), Chromosome(gene2)
6464

@@ -69,7 +69,7 @@ def mutate(self):
6969
will be created, but this original will not be affected.
7070
"""
7171
gene = list(self.gene)
72-
delta = randint(0, 89) + 32
72+
delta = randint(32, 121)
7373
idx = randint(0, len(gene) - 1)
7474
gene[idx] = chr((ord(gene[idx]) + delta) % 122)
7575

@@ -95,11 +95,11 @@ def gen_random():
9595
"""
9696
gene = []
9797
for x in range(len(Chromosome._target_gene)):
98-
gene.append(chr(randint(0, 89) + 32))
98+
gene.append(chr(randint(32, 121)))
9999

100100
return Chromosome(''.join(gene))
101101

102-
class Population(object):
102+
class Population:
103103
"""
104104
A class representing a population for a genetic algorithm simulation.
105105
@@ -128,9 +128,9 @@ def _tournament_selection(self):
128128
A helper method used to select a random chromosome from the
129129
population using a tournament selection algorithm.
130130
"""
131-
best = self.population[randint(0, len(self.population) - 1)]
131+
best = choice(self.population)
132132
for i in range(Population._tournamentSize):
133-
cont = self.population[randint(0, len(self.population) - 1)]
133+
cont = choice(self.population)
134134
if (cont.fitness < best.fitness): best = cont
135135

136136
return best
@@ -149,7 +149,7 @@ def evolve(self):
149149
"""
150150
size = len(self.population)
151151
idx = int(round(size * self.elitism))
152-
buf = self.population[0:idx]
152+
buf = self.population[:idx]
153153

154154
while (idx < size):
155155
if random() <= self.crossover:
@@ -168,7 +168,7 @@ def evolve(self):
168168
buf.append(self.population[idx])
169169
idx += 1
170170

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))
172172

173173
if __name__ == "__main__":
174174
maxGenerations = 16384

0 commit comments

Comments
 (0)