1import random
2import string
3
4def generate_random_solution(length=13):
5return [random.choice(string.printable) for _ in range(length)]
6
7def evaluate(solution):
8target = list("Hello, World!")
9diff = 0
10for i in range(len(target)):
11s = solution[i]
12t = target[i]
13diff += abs(ord(s) - ord(t))
14return diff
15
16def mutate_solution(solution):
17index = random.randint(0, len(solution) - 1)
18solution[index] = random.choice(string.printable)
19
20best = generate_random_solution()
21best_score = evaluate(best)
22
23while True:
24print('Best score so far', best_score, 'Solution', "".join(best))
25
26if best_score == 0:
27break
28
29new_solution = list(best)
30mutate_solution(new_solution)
31
32score = evaluate(new_solution)
33if evaluate(new_solution) < best_score:
34best = new_solution
35best_score = score
36