diff --git a/evolve_text.py b/evolve_text.py index e0202d2..63fde4a 100644 --- a/evolve_text.py +++ b/evolve_text.py @@ -5,7 +5,7 @@ http://deap.readthedocs.org Usage: - python evolve_text.py [goal_message] + python evolve_text.py [goal_message] Full instructions are at: https://sites.google.com/site/sd15spring/home/project-toolbox/evolutionary-algorithms @@ -19,6 +19,9 @@ from deap import base from deap import tools +# Experiment: increase the probability of substitution. This is where it seems to get stuck towards the end. It seems to help +# If it wasnt so late, I would look into changing the probabilities dynamically. + #----------------------------------------------------------------------------- # Global variables @@ -31,105 +34,145 @@ # Control whether all Messages are printed as they are evaluated VERBOSE = True +def levenshtein_distance(s1,s2, memo): + """ Computes the Levenshtein distance between two input strings """ + if memo.get((s1,s2), None) != None: + return memo[(s1,s2)] + if len(s1) == 0: + return len(s2) + if len(s2) == 0: + return len(s1) + value = min([int(s1[0] != s2[0]) + levenshtein_distance(s1[1:],s2[1:], memo), 1+levenshtein_distance(s1[1:],s2, memo), 1+levenshtein_distance(s1,s2[1:], memo)]) + memo[(s1,s2)] = value + return value + +def two_pt_crossover(s1, s2): + """ Returns a two point crossover of s1 and s2. It assumes len(s2) >= len(s1). """ + pt1 = random.randint(0, len(s1)-2) + pt2 = random.randint(pt1+1, len(s2)-1) # Garantees that 0<=pt1