forked from stinaq/WEASEL
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython.py
67 lines (49 loc) · 2.07 KB
/
python.py
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
import random
#returns either the same letter, or a random other, depending on mutation rate
def random_mutation(character, mutation_rate):
if random.random() < mutation_rate:
return random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ ')
return character
#take a parent string and make a child from it. How similar it is is dependent on mutation rate
def make_child(parent, mutation_rate):
child = ""
for character in parent:
child = child + random_mutation(character, mutation_rate)
return child
#decides how 'fit' the child is, how similar it is to the goal
def fitness(current, goal):
return sum(current[i] == goal[i] for i in range(len(goal)))
#takes a parent and makes a number of childen, returns the fittest one
def make_best_child(parent, goal, mutation_rate, number_of_children):
best_fitness = -1
best_child = ""
for child in range(0, number_of_children):
current_child = make_child(parent, mutation_rate)
current_fitness = fitness(current_child, goal)
if best_fitness < current_fitness:
best_child = current_child
best_fitness = current_fitness
return (best_child, best_fitness)
#sets the goal string, creates random start string, makes generations of children to find one that looks like the goal
def methinks(mutation_rate, number_of_children):
goal = "METHINKS IT IS LIKE A WEASEL"
goal_fitness = fitness(goal, goal)
current = ""
for i in range(0, len(goal)):
current = current + random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ ')
current_fitness = fitness(current, goal)
print(current)
generation_count = 1
while(goal_fitness != current_fitness):
(current, current_fitness) = make_best_child(current, goal,
mutation_rate, number_of_children)
generation_count = generation_count + 1
print(current)
print("finished at generation")
print(generation_count)
def main():
mutation_rate = 0.04
number_of_children = 100
methinks(mutation_rate, number_of_children)
if __name__ == '__main__':
main()