-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_evolution.py
More file actions
75 lines (63 loc) · 2.54 KB
/
string_evolution.py
File metadata and controls
75 lines (63 loc) · 2.54 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import evolution
import random
import string
import copy
class EvolvingString(evolution.EvolvingObject):
def __init__(self, string, goal_string, lineage=[]):
self.fitness = 0
self.string = string
self.goal = goal_string
self.lineage = lineage + [self.string]
self.child_style = self.swap_two_char_child
def determine_fitness(self):
self.fitness = 0
for i, char in enumerate(self.string):
if i < len(self.goal): # prevent index out of range
if char == self.goal[i]:
self.fitness += 1
return self.fitness
def create_child(self, count):
"""
creates children equal to 'count' with the function described by 'self.child_style'
:param count: int number of children
:return: list of children
"""
children = []
for x in range(count):
child = self.child_style()
children.append(child)
return children
def swap_two_char_child(self):
"""
swaps two of the characters in the string for random characters
:return: child `EvolvingString`
"""
"""child = copy.copy(self)
index = random.randint(0, len(child.goal))
child.string = child.string[0:index] + create_randstring(1) + child.string[index + 1:]
index = random.randint(0, len(child.goal))
child.string = child.string[0:index] + create_randstring(1) + child.string[index + 1:]
child.lineage.append(child.string)
return child """
index = random.randint(0, len(self.goal)-1)
new_string = self.string[0:index] + create_randstring(1) + self.string[index + 1:]
index = random.randint(0, len(self.goal)-1)
new_string = new_string[0:index] + create_randstring(1) + new_string[index + 1:]
if self.fitness == 0:
new_string = create_randstring(len(self.goal))
child = EvolvingString(new_string, self.goal, self.lineage)
return child
def create_randstring(length):
return ''.join(random.choices(string.ascii_letters + "_.!'[]{}() ", k=length))
def create_new_system_random_goal(length, set_size):
"""
:param length: (int) length of goal string
:param set_size: (int) size of each generation of the system
:return: `EvolutionSystem`
"""
initial_set = []
goal = create_randstring(length)
for x in range(set_size):
initial_set.append(EvolvingString(create_randstring(length), goal))
system = evolution.EvolutionSystem(initial_set)
return system