forked from willGuimont/SimpleGeneticAlgorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdna.py
More file actions
27 lines (23 loc) · 923 Bytes
/
Copy pathdna.py
File metadata and controls
27 lines (23 loc) · 923 Bytes
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
import random
class DNA:
def __init__(self, size: int, random_generator):
self.random_generator = random_generator
self.dna = [random_generator.gen() for _ in range(size)]
def crossover(self, other, self_probability=0.5):
self_size = len(self.dna)
assert self_size == len(other.dna)
new = DNA(self_size, self.random_generator)
for i in range(len(self.dna)):
if random.uniform(0, 1) < self_probability:
new.dna[i] = self.dna[i]
else:
new.dna[i] = other.dna[i]
return new
def mutated(self, mutation_rate: float):
self_size = len(self.dna)
new = DNA(self_size, self.random_generator)
new.dna = self.dna.copy()
for i in range(self_size):
if random.uniform(0, 1) < mutation_rate:
new.dna[i] = self.random_generator.gen()
return new