-
Notifications
You must be signed in to change notification settings - Fork 48
/
geneticQuoteJuly3.py
49 lines (39 loc) · 1.23 KB
/
geneticQuoteJuly3.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
'''Genetic Quote Editing
July 3, 2018'''
import random
target = "I never go back on my word, because that is my Ninja way."
characters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.',?!"
def makeList():
'''Returns a list of characters the same length as the target'''
charList = [random.choice(characters) for i in range(len(target))]
return charList
def score(myList):
'''Returns one integer: the number of matches with target'''
matches = 0
for i in range(len(target)):
if myList[i] == target[i]:
matches += 1
return matches
def mutate(mylist):
'''Returns mylist with one letter changed'''
newlist = list(mylist)
new_letter = random.choice(characters)
index = random.randint(0,len(target) - 1)
newlist[index] = new_letter
return newlist
random.seed()
bestList = makeList()
bestScore = score(bestList)
guesses = 0
improvements = 0
while True:
guess = mutate(bestList)
guessScore = score(guess)
guesses += 1
if guessScore <= bestScore:
continue
print(''.join(guess),guessScore,guesses)
if guessScore == len(target):
break
bestList = list(guess)
bestScore = guessScore