-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCrossoverOperator.py
More file actions
43 lines (24 loc) · 894 Bytes
/
CrossoverOperator.py
File metadata and controls
43 lines (24 loc) · 894 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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import random
from abc import ABCMeta, abstractmethod
class CrossoverOperator:
__metaclass__ = ABCMeta
@abstractmethod
def crossover(self, ch1, ch2):
pass
class OnePointCrossover(CrossoverOperator):
def crossover(self, ch1, ch2):
assert len(ch1) > 1
assert len(ch1) == len(ch2)
point = random.randint(1, len(ch1) - 1)
chr1 = ch1[:point] + ch2[point:]
chr2 = ch2[:point] + ch1[point:]
return chr1, chr2
class TwoPointsCrossover(CrossoverOperator):
def crossover(self, ch1, ch2):
assert len(ch1) > 2
assert len(ch1) == len(ch2)
point1 = random.randint(1, len(ch1) - 2)
point2 = random.randint(point1, len(ch1) - 1)
chr1 = ch1[:point1] + ch2[point1:point2] + ch1[point2:]
chr2 = ch2[:point1] + ch1[point1:point2] + ch2[point2:]
return chr1, chr2