From d9feae6213a5c8bc659d4fbbd28f01c1ffb7a6da Mon Sep 17 00:00:00 2001 From: Greg Eakin Date: Wed, 7 Feb 2018 17:36:40 -0800 Subject: [PATCH 01/19] Typos --- ch07/knightsTests.py | 6 +++--- ch17/regexTests.py | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/ch07/knightsTests.py b/ch07/knightsTests.py index ab39459..b232cc9 100644 --- a/ch07/knightsTests.py +++ b/ch07/knightsTests.py @@ -93,7 +93,7 @@ def test_3x4(self): width = 4 height = 3 # 1,0 2,0 3,0 - # 0,2 1,2 2,0 + # 0,2 1,2 2,2 # 2 N N N . # 1 . . . . # 0 . N N N @@ -111,8 +111,8 @@ def test_10x10(self): self.find_knight_positions(width, height, 22) def test_12x12(self): - width = 13 - height = 13 + width = 12 + height = 12 self.find_knight_positions(width, height, 28) def test_13x13(self): diff --git a/ch17/regexTests.py b/ch17/regexTests.py index 264429a..dc91206 100644 --- a/ch17/regexTests.py +++ b/ch17/regexTests.py @@ -357,7 +357,7 @@ def __init__(self, numWantedMatched, totalWanted, numUnwantedMatched, def __gt__(self, other): combined = (self._totalWanted - self.NumWantedMatched) \ + self.NumUnwantedMatched - otherCombined = (self._totalWanted - other.NumWantedMatched) \ + otherCombined = (other._totalWanted - other.NumWantedMatched) \ + other.NumUnwantedMatched if combined != otherCombined: return combined < otherCombined @@ -370,7 +370,7 @@ def __gt__(self, other): return self.Length < other.Length def __str__(self): - return "matches {} wanted {} unwanted, len {}".format( + return "matches: {} wanted, {} unwanted, len {}".format( "all" if self._totalWanted == self.NumWantedMatched else self.NumWantedMatched, self.NumUnwantedMatched, self.Length) From 33fb529d955f0c29ca75b3441ef8a615c238140a Mon Sep 17 00:00:00 2001 From: Greg Eakin Date: Wed, 7 Feb 2018 17:37:35 -0800 Subject: [PATCH 02/19] Fix the comparator --- ch09/knapsackTests.py | 6 +++++- ch13/approximatePiTests.py | 2 +- ch15/lawnmowerTests.py | 20 +++++++++++--------- 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/ch09/knapsackTests.py b/ch09/knapsackTests.py index 436c2e4..b589088 100644 --- a/ch09/knapsackTests.py +++ b/ch09/knapsackTests.py @@ -253,7 +253,11 @@ def __init__(self, totalWeight, totalVolume, totalValue): self.TotalValue = totalValue def __gt__(self, other): - return self.TotalValue > other.TotalValue + if self.TotalValue != other.TotalValue: + return self.TotalValue > other.TotalValue + if self.TotalWeight != other.TotalWeight: + return self.TotalWeight < other.TotalWeight + return self.TotalValue < other.TotalValue def __str__(self): return "wt: {:0.2f} vol: {:0.2f} value: {}".format( diff --git a/ch13/approximatePiTests.py b/ch13/approximatePiTests.py index 3b60424..573cfc9 100644 --- a/ch13/approximatePiTests.py +++ b/ch13/approximatePiTests.py @@ -90,7 +90,7 @@ def fnMutate(genes): best = genetic.get_best(fnGetFitness, length, optimalFitness, geneset, fnDisplay, fnMutate, maxAge=250, maxSeconds=maxSeconds) - return best.Fitness >= optimalFitness + return optimalFitness <= best.Fitness def test_optimize(self): geneset = [i for i in range(1, 512 + 1)] diff --git a/ch15/lawnmowerTests.py b/ch15/lawnmowerTests.py index d4e0d3c..a712c24 100644 --- a/ch15/lawnmowerTests.py +++ b/ch15/lawnmowerTests.py @@ -45,6 +45,7 @@ def mutate(genes, geneSet, minGenes, maxGenes, fnGetFitness, maxRounds): count -= 1 if fnGetFitness(genes) > initialFitness: return + adding = len(genes) == 0 or \ (len(genes) < maxGenes and random.randint(0, 5) == 0) if adding: @@ -236,7 +237,7 @@ def fnMutate(child): fnDisplay, fnMutate, fnCreate, maxAge=None, poolSize=10, crossover=crossover) - self.assertTrue(not best.Fitness > optimalFitness) + self.assertTrue(not optimalFitness > best.Fitness) class Mow: @@ -342,6 +343,7 @@ def __init__(self, genes): if type(temp[index]) is Call: temp[index].Funcs = funcs + if type(temp[index]) is Func: if len(funcs) > 0 and not temp[index].ExpectCall: temp[index] = Call() @@ -369,14 +371,14 @@ def __init__(self, genes): len(funcs[func_id].Ops) == 0: del func.Ops[index] - for index in reversed(range(len(temp))): - if type(temp[index]) is Call: - func_id = temp[index].FuncId - if func_id is None: - continue - if func_id >= len(funcs) or \ - len(funcs[func_id].Ops) == 0: - del temp[index] + for index in reversed(range(len(temp))): + if type(temp[index]) is Call: + func_id = temp[index].FuncId + if func_id is None: + continue + if func_id >= len(funcs) or \ + len(funcs[func_id].Ops) == 0: + del temp[index] self.Main = temp self.Funcs = funcs From 54078b42bca505396e3cd3b75249b58171664440 Mon Sep 17 00:00:00 2001 From: Greg Eakin Date: Wed, 7 Feb 2018 17:38:11 -0800 Subject: [PATCH 03/19] Don't move the elements back to where the were. --- ch18/ticTacToeTests.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ch18/ticTacToeTests.py b/ch18/ticTacToeTests.py index 1c19c5b..2e931e0 100644 --- a/ch18/ticTacToeTests.py +++ b/ch18/ticTacToeTests.py @@ -200,6 +200,8 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) + if index >= start + index += 1 genes[index:index] = toMove return True From 805d8b9dd208de41c9b3e83e8433c7464066a7aa Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Thu, 8 Feb 2018 08:19:32 -0600 Subject: [PATCH 04/19] propagate Greg Eakin's suggestions, corrections and improvements over to the Spanish language tree --- es/ch07/caballos.py | 6 +++--- es/ch09/mochila.py | 7 ++++++- es/ch13/pi.py | 2 +- es/ch15/pruebas.py | 18 +++++++++--------- es/ch17/regex.py | 4 ++-- es/ch18/ticTacToe.py | 2 ++ 6 files changed, 23 insertions(+), 16 deletions(-) diff --git a/es/ch07/caballos.py b/es/ch07/caballos.py index c30641b..609f974 100644 --- a/es/ch07/caballos.py +++ b/es/ch07/caballos.py @@ -96,7 +96,7 @@ def test_3x4(self): anchura = 4 altura = 3 # 1,0 2,0 3,0 - # 0,2 1,2 2,0 + # 0,2 1,2 2,2 # 2 C C C . # 1 . . . . # 0 . C C C @@ -114,8 +114,8 @@ def test_10x10(self): self.encontrarCaballoPosiciones(anchura, altura, 22) def test_12x12(self): - anchura = 13 - altura = 13 + anchura = 12 + altura = 12 self.encontrarCaballoPosiciones(anchura, altura, 28) def test_13x13(self): diff --git a/es/ch09/mochila.py b/es/ch09/mochila.py index d6aec76..520cf43 100644 --- a/es/ch09/mochila.py +++ b/es/ch09/mochila.py @@ -261,7 +261,12 @@ def __init__(self, pesoTotal, volumenTotal, valorTotal): self.ValorTotal = valorTotal def __gt__(self, otro): - return self.ValorTotal > otro.ValorTotal + if self.ValorTotal != otro.ValorTotal: + return self.ValorTotal > otro.ValorTotal + if self.PesoTotal != otro.PesoTotal: + return self.PesoTotal < otro.PesoTotal + return self.VolumenTotal < otro.VolumenTotal + def __str__(self): return "peso: {:0.2f} vol: {:0.2f} valor: {}".format( diff --git a/es/ch13/pi.py b/es/ch13/pi.py index ae0e0ba..b5b5e96 100644 --- a/es/ch13/pi.py +++ b/es/ch13/pi.py @@ -91,7 +91,7 @@ def fnMudar(genes): aptitudÓptima, geneSet, fnMostrar, fnMudar, edadMáxima=250, segundosMáximos=segundosMáximos) - return mejor.Aptitud >= aptitudÓptima + return aptitudÓptima <= mejor.Aptitud def test_optimize(self): geneSet = [i for i in range(1, 512 + 1)] diff --git a/es/ch15/pruebas.py b/es/ch15/pruebas.py index 27c2851..4a009c4 100644 --- a/es/ch15/pruebas.py +++ b/es/ch15/pruebas.py @@ -245,7 +245,7 @@ def fnMudar(niño): edadMáxima=None, tamañoDePiscina=10, intercambiar=intercambiar) - self.assertTrue(not mejor.Aptitud > aptitudÓptima) + self.assertTrue(not aptitudÓptima > mejor.Aptitud) class Corta: @@ -379,14 +379,14 @@ def __init__(self, genes): len(funcs[func_id].Instrucciones) == 0: del func.Instrucciones[índice] - for índice in reversed(range(len(temp))): - if type(temp[índice]) is Llama: - func_id = temp[índice].FuncId - if func_id is None: - continue - if func_id >= len(funcs) or \ - len(funcs[func_id].Instrucciones) == 0: - del temp[índice] + for índice in reversed(range(len(temp))): + if type(temp[índice]) is Llama: + func_id = temp[índice].FuncId + if func_id is None: + continue + if func_id >= len(funcs) or \ + len(funcs[func_id].Instrucciones) == 0: + del temp[índice] self.Principal = temp self.Funcs = funcs diff --git a/es/ch17/regex.py b/es/ch17/regex.py index 481ea85..c2eb1b5 100644 --- a/es/ch17/regex.py +++ b/es/ch17/regex.py @@ -364,7 +364,7 @@ def __gt__(self, otro): conjunto = (self._totalDeseado - self.NúmeroDeDeseadosQueCoincidieron) + \ self.NúmeroDeNoDeseadosQueCoincidieron - otroConjunto = (self._totalDeseado - + otroConjunto = (otro._totalDeseado - otro.NúmeroDeDeseadosQueCoincidieron) + \ otro.NúmeroDeNoDeseadosQueCoincidieron if conjunto != otroConjunto: @@ -379,7 +379,7 @@ def __gt__(self, otro): return self.Longitud < otro.Longitud def __str__(self): - return "coincide con {} deseadas y {} no deseadas, lon {}".format( + return "coincide con: {} deseadas y, {} no deseadas, lon {}".format( "todas" if self._totalDeseado == self.NúmeroDeDeseadosQueCoincidieron else self.NúmeroDeDeseadosQueCoincidieron, diff --git a/es/ch18/ticTacToe.py b/es/ch18/ticTacToe.py index 1c9e36b..4b3ce0d 100644 --- a/es/ch18/ticTacToe.py +++ b/es/ch18/ticTacToe.py @@ -200,6 +200,8 @@ def mudar_mover(genes): aMover = genes[principio:fin] genes[principio:fin] = [] índice = random.choice(range(len(genes))) + if índice >= principio: + índice += 1 genes[índice:índice] = aMover return True From 62a8f459fb77760082374f64a1a7012945dc421f Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Thu, 8 Feb 2018 09:05:41 -0600 Subject: [PATCH 05/19] fix typo from pull request --- ch18/ticTacToeTests.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ch18/ticTacToeTests.py b/ch18/ticTacToeTests.py index 2e931e0..26486f4 100644 --- a/ch18/ticTacToeTests.py +++ b/ch18/ticTacToeTests.py @@ -200,7 +200,7 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) - if index >= start + if index >= start: index += 1 genes[index:index] = toMove return True From 01b8ac0a0bac3e35423be58731c178c56495ec0c Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Thu, 8 Feb 2018 09:34:13 -0600 Subject: [PATCH 06/19] ch17,18 improve mutate_move/mudar_mover --- ch17/regexTests.py | 2 ++ ch18/ticTacToeTests.py | 2 +- es/ch17/regex.py | 2 ++ es/ch18/ticTacToe.py | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/ch17/regexTests.py b/ch17/regexTests.py index dc91206..4c2f611 100644 --- a/ch17/regexTests.py +++ b/ch17/regexTests.py @@ -169,6 +169,8 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) + if index == start: + index += 1 genes[index:index] = toMove return True diff --git a/ch18/ticTacToeTests.py b/ch18/ticTacToeTests.py index 26486f4..a22343e 100644 --- a/ch18/ticTacToeTests.py +++ b/ch18/ticTacToeTests.py @@ -200,7 +200,7 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) - if index >= start: + if index == start: index += 1 genes[index:index] = toMove return True diff --git a/es/ch17/regex.py b/es/ch17/regex.py index c2eb1b5..eee06ea 100644 --- a/es/ch17/regex.py +++ b/es/ch17/regex.py @@ -170,6 +170,8 @@ def mudar_mover(genes): aMover = genes[principio:fin] genes[principio:fin] = [] índice = random.choice(range(len(genes))) + if índice == principio: + índice += 1 genes[índice:índice] = aMover return True diff --git a/es/ch18/ticTacToe.py b/es/ch18/ticTacToe.py index 4b3ce0d..fce08f0 100644 --- a/es/ch18/ticTacToe.py +++ b/es/ch18/ticTacToe.py @@ -200,7 +200,7 @@ def mudar_mover(genes): aMover = genes[principio:fin] genes[principio:fin] = [] índice = random.choice(range(len(genes))) - if índice >= principio: + if índice == principio: índice += 1 genes[índice:índice] = aMover return True From 4f6621f374e2f4ce8139179be50455481c044215 Mon Sep 17 00:00:00 2001 From: Greg Eakin Date: Sat, 10 Feb 2018 09:10:08 -0800 Subject: [PATCH 07/19] Clarify and fix which age gets reset in the Get Improvement function. --- ch08/genetic.py | 8 ++++---- ch12/genetic.py | 8 ++++---- ch13/genetic.py | 8 ++++---- ch16/genetic.py | 8 ++++---- ch18/genetic.py | 8 ++++---- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/ch08/genetic.py b/ch08/genetic.py index 855b163..875bbd7 100644 --- a/ch08/genetic.py +++ b/ch08/genetic.py @@ -90,20 +90,20 @@ def _get_improvement(new_child, generate_parent, maxAge): if random.random() < exp(-proportionSimilar): parent = child continue + bestParent.Age = 0 parent = bestParent - parent.Age = 0 continue if not child.Fitness > parent.Fitness: # same fitness child.Age = parent.Age + 1 parent = child continue + child.Age = 0 parent = child - parent.Age = 0 if child.Fitness > bestParent.Fitness: - yield child bestParent = child - historicalFitnesses.append(child.Fitness) + yield bestParent + historicalFitnesses.append(bestParent.Fitness) class Chromosome: diff --git a/ch12/genetic.py b/ch12/genetic.py index afe5a99..dc5c89c 100644 --- a/ch12/genetic.py +++ b/ch12/genetic.py @@ -139,20 +139,20 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize): if random.random() < exp(-proportionSimilar): parents[pindex] = child continue + bestParent.Age = 0 parents[pindex] = bestParent - parent.Age = 0 continue if not child.Fitness > parent.Fitness: # same fitness child.Age = parent.Age + 1 parents[pindex] = child continue + child.Age = 0 parents[pindex] = child - parent.Age = 0 if child.Fitness > bestParent.Fitness: - yield child bestParent = child - historicalFitnesses.append(child.Fitness) + yield bestParent + historicalFitnesses.append(bestParent.Fitness) class Chromosome: diff --git a/ch13/genetic.py b/ch13/genetic.py index 22d688e..d040846 100644 --- a/ch13/genetic.py +++ b/ch13/genetic.py @@ -148,20 +148,20 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, maxSeconds): if random.random() < exp(-proportionSimilar): parents[pindex] = child continue + bestParent.Age = 0 parents[pindex] = bestParent - parent.Age = 0 continue if not child.Fitness > parent.Fitness: # same fitness child.Age = parent.Age + 1 parents[pindex] = child continue + child.Age = 0 parents[pindex] = child - parent.Age = 0 if child.Fitness > bestParent.Fitness: - yield False, child bestParent = child - historicalFitnesses.append(child.Fitness) + yield False, bestParent + historicalFitnesses.append(bestParent.Fitness) class Chromosome: diff --git a/ch16/genetic.py b/ch16/genetic.py index e43681d..16a9841 100644 --- a/ch16/genetic.py +++ b/ch16/genetic.py @@ -149,20 +149,20 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, if random.random() < exp(-proportionSimilar): parents[pindex] = child continue + bestParent.Age = 0 parents[pindex] = bestParent - parent.Age = 0 continue if not child.Fitness > parent.Fitness: # same fitness child.Age = parent.Age + 1 parents[pindex] = child continue + child.Age = 0 parents[pindex] = child - parent.Age = 0 if child.Fitness > bestParent.Fitness: - yield False, child bestParent = child - historicalFitnesses.append(child.Fitness) + yield False, bestParent + historicalFitnesses.append(bestParent.Fitness) def hill_climbing(optimizationFunction, is_improvement, is_optimal, diff --git a/ch18/genetic.py b/ch18/genetic.py index f469e18..7c6d815 100644 --- a/ch18/genetic.py +++ b/ch18/genetic.py @@ -150,20 +150,20 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, if random.random() < exp(-proportionSimilar): parents[pindex] = child continue + bestParent.Age = 0 parents[pindex] = bestParent - parent.Age = 0 continue if not child.Fitness > parent.Fitness: # same fitness child.Age = parent.Age + 1 parents[pindex] = child continue + child.Age = 0 parents[pindex] = child - parent.Age = 0 if child.Fitness > bestParent.Fitness: - yield False, child bestParent = child - historicalFitnesses.append(child.Fitness) + yield False, bestParent + historicalFitnesses.append(bestParent.Fitness) def hill_climbing(optimizationFunction, is_improvement, is_optimal, From 71fa9402bd48420931d86ac2a61b63c93230b983 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Sat, 10 Feb 2018 13:06:37 -0600 Subject: [PATCH 08/19] add .gitignore --- .gitignore | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..854cb64 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +images +output +**/__pycache__/* +/.idea +**/.cache/* +*.ukp \ No newline at end of file From 9aade014408f2894a769e168f6eb8402e876ce28 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Sat, 10 Feb 2018 13:09:34 -0600 Subject: [PATCH 09/19] propagate Greg Eakin's Age clarifications to the Spanish language tree --- es/ch08/genetic.py | 8 ++++---- es/ch12/genetic.py | 8 ++++---- es/ch13/genetic.py | 8 ++++---- es/ch16/genetic.py | 8 ++++---- es/ch18/genetic.py | 8 ++++---- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/es/ch08/genetic.py b/es/ch08/genetic.py index a5a5c88..0815864 100644 --- a/es/ch08/genetic.py +++ b/es/ch08/genetic.py @@ -93,20 +93,20 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima): if random.random() < exp(-proporciónSimilar): padre = niño continue + mejorPadre.Edad = 0 padre = mejorPadre - padre.Edad = 0 continue if not niño.Aptitud > padre.Aptitud: # mismo aptitud niño.Edad = padre.Edad + 1 padre = niño continue + niño.Edad = 0 padre = niño - padre.Edad = 0 if niño.Aptitud > mejorPadre.Aptitud: - yield niño mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) + yield mejorPadre + aptitudesHistóricas.append(mejorPadre.Aptitud) class Cromosoma: diff --git a/es/ch12/genetic.py b/es/ch12/genetic.py index 7b71058..1703276 100644 --- a/es/ch12/genetic.py +++ b/es/ch12/genetic.py @@ -143,20 +143,20 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina): if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue + mejorPadre.Edad = 0 padres[pÍndice] = mejorPadre - padre.Edad = 0 continue if not niño.Aptitud > padre.Aptitud: # mismo aptitud niño.Edad = padre.Edad + 1 padres[pÍndice] = niño continue + niño.Edad = 0 padres[pÍndice] = niño - padre.Edad = 0 if niño.Aptitud > mejorPadre.Aptitud: - yield niño mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) + yield mejorPadre + aptitudesHistóricas.append(mejorPadre.Aptitud) class Cromosoma: diff --git a/es/ch13/genetic.py b/es/ch13/genetic.py index f952e8d..e42a1ed 100644 --- a/es/ch13/genetic.py +++ b/es/ch13/genetic.py @@ -155,20 +155,20 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue + mejorPadre.Edad = 0 padres[pÍndice] = mejorPadre - padre.Edad = 0 continue if not niño.Aptitud > padre.Aptitud: # mismo aptitud niño.Edad = padre.Edad + 1 padres[pÍndice] = niño continue + niño.Edad = 0 padres[pÍndice] = niño - padre.Edad = 0 if niño.Aptitud > mejorPadre.Aptitud: - yield False, niño mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) + yield False, mejorPadre + aptitudesHistóricas.append(mejorPadre.Aptitud) class Cromosoma: diff --git a/es/ch16/genetic.py b/es/ch16/genetic.py index b114b25..7b4c155 100644 --- a/es/ch16/genetic.py +++ b/es/ch16/genetic.py @@ -155,20 +155,20 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue + mejorPadre.Edad = 0 padres[pÍndice] = mejorPadre - padre.Edad = 0 continue if not niño.Aptitud > padre.Aptitud: # mismo aptitud niño.Edad = padre.Edad + 1 padres[pÍndice] = niño continue + niño.Edad = 0 padres[pÍndice] = niño - padre.Edad = 0 if niño.Aptitud > mejorPadre.Aptitud: - yield False, niño mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) + yield False, mejorPadre + aptitudesHistóricas.append(mejorPadre.Aptitud) def ascenso_de_la_colina(funciónDeOptimización, es_mejora, es_óptimo, diff --git a/es/ch18/genetic.py b/es/ch18/genetic.py index dffb546..5915205 100644 --- a/es/ch18/genetic.py +++ b/es/ch18/genetic.py @@ -156,20 +156,20 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue + mejorPadre.Edad = 0 padres[pÍndice] = mejorPadre - padre.Edad = 0 continue if not niño.Aptitud > padre.Aptitud: # mismo aptitud niño.Edad = padre.Edad + 1 padres[pÍndice] = niño continue + niño.Edad = 0 padres[pÍndice] = niño - padre.Edad = 0 if niño.Aptitud > mejorPadre.Aptitud: - yield False, niño mejorPadre = niño - aptitudesHistóricas.append(niño.Aptitud) + yield False, mejorPadre + aptitudesHistóricas.append(mejorPadre.Aptitud) def ascenso_de_la_colina(funciónDeOptimización, es_mejora, es_óptimo, From 7ffe1214528c7a922573437275fea3ab3abd8451 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Wed, 14 Feb 2018 08:17:16 -0600 Subject: [PATCH 10/19] ch17,18 use >= vice == in mutate_move/mudar_mover - provides more diversity in the results per Greg Eakin see: https://dotnetfiddle.net/ko2TgS --- ch17/regexTests.py | 2 +- ch18/ticTacToeTests.py | 2 +- es/ch17/regex.py | 2 +- es/ch18/ticTacToe.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ch17/regexTests.py b/ch17/regexTests.py index 4c2f611..39d654d 100644 --- a/ch17/regexTests.py +++ b/ch17/regexTests.py @@ -169,7 +169,7 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) - if index == start: + if index >= start: index += 1 genes[index:index] = toMove return True diff --git a/ch18/ticTacToeTests.py b/ch18/ticTacToeTests.py index a22343e..26486f4 100644 --- a/ch18/ticTacToeTests.py +++ b/ch18/ticTacToeTests.py @@ -200,7 +200,7 @@ def mutate_move(genes): toMove = genes[start:stop] genes[start:stop] = [] index = random.choice(range(len(genes))) - if index == start: + if index >= start: index += 1 genes[index:index] = toMove return True diff --git a/es/ch17/regex.py b/es/ch17/regex.py index eee06ea..fe8aa50 100644 --- a/es/ch17/regex.py +++ b/es/ch17/regex.py @@ -170,7 +170,7 @@ def mudar_mover(genes): aMover = genes[principio:fin] genes[principio:fin] = [] índice = random.choice(range(len(genes))) - if índice == principio: + if índice >= principio: índice += 1 genes[índice:índice] = aMover return True diff --git a/es/ch18/ticTacToe.py b/es/ch18/ticTacToe.py index fce08f0..4b3ce0d 100644 --- a/es/ch18/ticTacToe.py +++ b/es/ch18/ticTacToe.py @@ -200,7 +200,7 @@ def mudar_mover(genes): aMover = genes[principio:fin] genes[principio:fin] = [] índice = random.choice(range(len(genes))) - if índice == principio: + if índice >= principio: índice += 1 genes[índice:índice] = aMover return True From b6edd507e76251fe24cb955a8de0386dc6b70c31 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Wed, 14 Feb 2018 08:21:01 -0600 Subject: [PATCH 11/19] the English edition is now available in hardcover https://www.amazon.com/Genetic-Algorithms-Python-Clinton-Sheppard/dp/1732029806/ ISBN-13: 978-1-7320298-0-4 --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 4fe048f..42a46d5 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Genetic algorithms are one of the tools you can use to apply machine learning to Available from major stores including Amazon, Apple and Barnes & Noble, in paperback, ePub, Kindle and PDF formats. - https://www.amazon.com/Genetic-Algorithms-Python-Clinton-Sheppard/dp/1540324001/ ISBN-13: 978-1-540324-00-9 (paperback) +- https://www.amazon.com/Genetic-Algorithms-Python-Clinton-Sheppard/dp/1732029806/ ISBN-13: 978-1-7320298-0-4 (hardcover) - https://itunes.apple.com/us/book/genetic-algorithms-with-python/id1231392098 ISBN-13: 978-1-370764-62-4 (ePub) - https://www.amazon.com/dp/B01MYOWVJ2/ (Kindle Edition) - https://leanpub.com/genetic_algorithms_with_python (PDF) From d005d9a983958a2d33f0a1ab5dd3b41b3467f257 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Mon, 24 Sep 2018 07:16:44 -0500 Subject: [PATCH 12/19] update Spanish translation --- es/README.md | 65 ++++++++++++++-------------- "es/ch03/n\303\272merosOrdenados.py" | 2 +- 2 files changed, 33 insertions(+), 34 deletions(-) diff --git a/es/README.md b/es/README.md index 77fad65..a1325bb 100644 --- a/es/README.md +++ b/es/README.md @@ -7,9 +7,9 @@ Descripción [English edition](https://github.com/handcraftsman/GeneticAlgorithmsWithPython#description) tapa del libro Algoritmos Genéticos con Python -Obtenga una introducción práctica al aprendizaje de la máquina con algoritmos genéticos usando Python. Tutoriales paso a paso construye sus habilidades de ¡Hola Mundo! a optimizar un algoritmo genético con otro, y finalmente a la programación genética; así, preparándose para aplicar algoritmos genéticos a problemas en su propio campo de experiencia. +Obtén una introducción práctica al aprendizaje automático con los algoritmos genéticos usando Python. Los tutoriales paso a paso desarrollan tus habilidades desde el ¡Hola Mundo! hasta optimizar un algoritmo genético con otro y, finalmente, la programación genética; preparándote así para aplicar los algoritmos genéticos a problemas de tu propio campo de especialización. -Algoritmos genéticos son una de las herramientas que puede utilizar para aplicar el aprendizaje de la máquina a la búsqueda de soluciones buenas, a veces incluso óptimas, a los problemas que tienen miles de millones de soluciones potenciales. Este libro le da la experiencia de hacer que los algoritmos genéticos funcionen para usted, usando los problemas fáciles de seguir del ejemplo que usted puede recurrir al aprender a usar otras herramientas y técnicas de aprendizaje de la máquina. Cada capítulo es un tutorial paso a paso que ayuda a desarrollar sus habilidades en el uso de algoritmos genéticos para resolver problemas utilizando Python. +Los algoritmos genéticos son una de las herramientas que puedes usar para aplicar el aprendizaje automático al hallazgo de soluciones buenas (a veces incluso óptimas) a problemas que tienen miles de millones de soluciones posibles. Este libro te ofrece experiencia en hacer que los algoritmos genéticos funcionen, usando proyectos de ejemplo fáciles de seguir a los que puedes recurrir cuando aprendas a usar otras herramientas y técnicas de aprendizaje automático. Cada capítulo es un tutorial paso a paso que te ayuda a desarrollar tus habilidades en el uso de los algoritmos genéticos para resolver problemas usando Python. - https://www.amazon.com/dp/1548125180/ ISBN-13: 978-1-548125-18-9 (Edición en tapa blanda) - https://www.amazon.com/dp/B072NDMJ4L (Versión Kindle) @@ -20,56 +20,55 @@ Tabla de contenido Una breve introducción a los algoritmos genéticos Capítulo 1: ¡Hola Mundo! -- Adivine una contraseña dando el número de letras correctas en el grupo. Construir un motor de mutación. +- Adivina una contraseña dado el número de letras correctas en la conjetura. Construye un motor de mutación. Capítulo 2: El Problema One-max -- Produce una matriz de bits donde todos son 1s. Expande el motor para funcionar con cualquier tipo de gene. +- Produce un arreglo de bits donde todos son unos. Expande el motor para funcionar con cualquier tipo de gen. -Capítulo 3: Números ordenados -- Produsca una matriz de números enteros ordenados. Demuestre el manejo de múltiples metas y restricciones entre los genes. +Capítulo 3: Números ordenados +- Produce un arreglo de enteros ordenados. Demuestra el manejo de múltiples objetivos y restricciones de aptitud entre genes. -Capítulo 4: El rompecabezas de 8 reinas -- Encuentre las posiciones seguras de la reina en un tablero de ajedrez de 8x8 y luego amplíe a NxN. Demuestre la diferencia entre el fenotipo y el genotipo. +Capítulo 4: El problema de las ocho reinas +- Encuentra posiciones seguras para las reinas en un tablero de 8x8 y luego expande a NxN. Demuestra la diferencia entre fenotipo y genotipo. Ver el código de muestra. -Capítulo 5: Coloración gráfica -- Coloree un mapa de los países donde Español es el idioma nacional usando solamente 4 colores. Introdusca grupos de datos comunes y trabaje con archivos. También introdusca el uso de reglas para funcionar con restricciones genéticas. +Capítulo 5: Coloración de grafos +- Colorea un mapa de países donde el español es el idioma nacional usando sólo 4 colores. Introduce conjuntos de datos estándar y trabajo con archivos. También introduce el uso de reglas para trabajar con las restricciones de los genes. -Capítulo 6: Problema de la carta -- Más restricciones genéticas. Introdusca la mutación personalizada, los algoritmos meméticos, y la técnica de suma-de-diferencia. También demuestre un cromosoma donde la forma en que se utiliza un gene depende de su posición en la matriz génica. +Capítulo 6: El problema de las cartas +- Más restricciones genéticas. Introduce la mutación personalizada, los algoritmos meméticos y la técnica de la suma por diferencia. También muestra un cromosoma en el que la manera de usar un gen depende de su posición en el arreglo de genes. -Capítulo 7: Problema de los caballos de ajedrez -- Encuentre el número mínimo de caballos necesarios para atacar todas las posiciones en un tablero de ajedrez. Presente genes personalizados y creación de matrices de genes. También demuestra mínimos y máximos locales. +Capítulo 7: El problema de los caballos +- Encuentra el número mínimo de caballos que hacen falta para atacar todas las posiciones en un tablero. Introduce los genes personalizados y la creación de arreglos de genes. También demuestra los mínimos y máximos locales. Capítulo 8: Cuadrados mágicos -- Encuentre cuadrados donde todas las filas, columnas y ambas diagonales de una matriz de NxN tienen la misma suma. Introduce el recocido simulado. +- Encuentra cuadrados en los que todas las filas, columnas y ambas diagonales de una matriz de NxN tengan la misma suma. Introduce el recocido simulado. -Capítulo 9: Problema de la mochila -- Optimizar el contenido de un contenedor para una o más variables. Presenta rama y límite y los cromosomas de la longitud variable. +Capítulo 9: El problema de la mochila +- Optimiza el contenido de un recipiente para una o más variables. Introduce la ramificación y poda, así como los cromosomas de longitud variable. -Capítulo 10: Resolución de ecuaciones lineales -- Encuentre las soluciones de ecuaciones lineales con 2, 3 y 4 desconocidos. Variación de ramas y límite. Refuerza la flexibilidad del genotipo. +Capítulo 10: Resolver ecuaciones lineales +- Encuentra las soluciones de las ecuaciones lineales con 2, 3 y 4 incógnitas. Variación de ramificación y poda. Refuerza la flexibilidad del genotipo. -Capítulo 11: Generando Sudoku -- Un ejercicio guiado en la generación de rompecabezas de Sudoku. +Capítulo 11: Generación de Sudoku +- Un ejercicio guiado para generar rompecabezas sudoku. -Capítulo 12: Problema del vendedor viajero -- Encuentre la ruta óptima para visitar las ciudades. Introduce intercambio de genes y una piscina de padres. +Capítulo 12: El problema del viajante +- Encuentra la ruta óptima para visitar ciudades. Introduce la recombinación y una reserva de padres. -Capítulo 13: Aproximación de Pi -- Encuentre los dos números de 10 bits cuyo dividendo es el más cercano a Pi. Introdusca utilizando un algoritmo genético para afinar otro. +Capítulo 13: Aproximarse a Pi +- Encuentra los dos números de 10 bits cuyo dividendo está más cerca de Pi. Introduce el uso de un algoritmo genético para optimizar otro. Capítulo 14: Generación de ecuaciones -- Encuentre la ecuación más corta que produzca un resultado específico usando suma, resta, multiplicación, etc. Introduce la programación genética simbólica. +- Encuentra la ecuación más corta que produce un resultado específico usando la suma, la resta, la multiplicación, etc. Introduce la programación genética simbólica. -Capítulo 15: Problema de la cortadora de pasto -- Genere una serie de instrucciones que hacen que una cortadora de pasto corte un campo de pasto. Programación genética con estructuras de control, objetos, y funciones definidas automáticamentes. +Capítulo 15: El problema de la cortadora de césped +- Genera una serie de instrucciones que hacen que una cortadora de césped corte un campo de césped. Programación genética con estructuras de control, objetos y funciones definidas automáticamente (FDAs). Capítulo 16: Circuitos lógicos -- Construya circuitos que se comporten como puertas lógicas básicas, combinaciones de compuertas, y finalmente un sumador de 2 bits que utilice nodos de árbol y ascenso de la colina. +- Genera circuitos que se comportan como puertas básicas, combinaciones de puertas y finalmente un sumador de 2 bits. Introduce los nodos de árboles y los algoritmos de escalada. Capítulo 17: Expresiones regulares -- Busque expresiones regulares que coincidan con las cadenas deseadas. Presente la reparación cromosómica y el control del crecimiento. - -Capítulo 18: Tic-tac-toe -- Crear reglas para jugar el juego sin perder. Presenta la selección de torneos. +- Encuentra expresiones regulares que coincidan con las cadenas buscadas. Introduce la reparación de cromosomas y el control de crecimiento. +Capítulo 18: Tres en raya +- Crea reglas para jugar al juego sin perder. Introduce la selección por torneos. diff --git "a/es/ch03/n\303\272merosOrdenados.py" "b/es/ch03/n\303\272merosOrdenados.py" index 3b57712..2689d28 100644 --- "a/es/ch03/n\303\272merosOrdenados.py" +++ "b/es/ch03/n\303\272merosOrdenados.py" @@ -77,7 +77,7 @@ def __gt__(self, otro): return self.BrechaTotal < otro.BrechaTotal def __str__(self): - return "{} en secuencia, {} brecha".format( + return "{} secuencial, distancia {}".format( self.NúmerosEnSecuencia, self.BrechaTotal) From 1c041c05e512452ee1b96811fcc2cf2d7b8b3cec Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Fri, 30 Nov 2018 09:20:38 -0600 Subject: [PATCH 13/19] spanish code: mudar => mutar --- es/ch01/genetic.py | 4 +-- es/ch02/genetic.py | 4 +-- es/ch03/genetic.py | 8 ++--- es/ch06/cartas.py | 8 ++--- es/ch06/genetic.py | 14 ++++----- es/ch07/caballos.py | 8 ++--- es/ch07/genetic.py | 14 ++++----- "es/ch08/cuadradosM\303\241gicos.py" | 8 ++--- es/ch08/genetic.py | 14 ++++----- es/ch09/mochila.py | 9 +++--- es/ch10/ecuacionesLineales.py | 8 ++--- es/ch11/sudoku.py | 8 ++--- es/ch12/genetic.py | 22 ++++++------- es/ch12/vendedor.py | 8 ++--- es/ch13/genetic.py | 22 ++++++------- es/ch13/pi.py | 8 ++--- es/ch14/ecuaciones.py | 8 ++--- es/ch15/pruebas.py | 8 ++--- es/ch16/genetic.py | 22 ++++++------- es/ch16/pruebas.py | 8 ++--- es/ch17/regex.py | 46 ++++++++++++++-------------- es/ch18/genetic.py | 22 ++++++------- es/ch18/ticTacToe.py | 46 ++++++++++++++-------------- 23 files changed, 163 insertions(+), 164 deletions(-) diff --git a/es/ch01/genetic.py b/es/ch01/genetic.py index 90bf08c..2b7417f 100644 --- a/es/ch01/genetic.py +++ b/es/ch01/genetic.py @@ -31,7 +31,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): índice = random.randrange(0, len(padre.Genes)) genesDelNiño = list(padre.Genes) nuevoGen, alterno = random.sample(geneSet, 2) @@ -50,7 +50,7 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, if mejorPadre.Aptitud >= aptitudÓptima: return mejorPadre while True: - niño = _mudar(mejorPadre, geneSet, obtener_aptitud) + niño = _mutar(mejorPadre, geneSet, obtener_aptitud) if mejorPadre.Aptitud >= niño.Aptitud: continue mostrar(niño) diff --git a/es/ch02/genetic.py b/es/ch02/genetic.py index 175079b..803b841 100644 --- a/es/ch02/genetic.py +++ b/es/ch02/genetic.py @@ -30,7 +30,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -48,7 +48,7 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, if mejorPadre.Aptitud >= aptitudÓptima: return mejorPadre while True: - niño = _mudar(mejorPadre, geneSet, obtener_aptitud) + niño = _mutar(mejorPadre, geneSet, obtener_aptitud) if mejorPadre.Aptitud >= niño.Aptitud: continue mostrar(niño) diff --git a/es/ch03/genetic.py b/es/ch03/genetic.py index 457274f..f4cd5dc 100644 --- a/es/ch03/genetic.py +++ b/es/ch03/genetic.py @@ -30,7 +30,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -44,13 +44,13 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, mostrar): random.seed() - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) def fnGenerarPadre(): return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - for mejora in _obtener_mejoras(fnMudar, fnGenerarPadre): + for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): mostrar(mejora) if not aptitudÓptima > mejora.Aptitud: return mejora diff --git a/es/ch06/cartas.py b/es/ch06/cartas.py index b222254..a90b8b1 100644 --- a/es/ch06/cartas.py +++ b/es/ch06/cartas.py @@ -40,7 +40,7 @@ def mostrar(candidato, horaInicio): diferencia)) -def mudar(genes, geneSet): +def mutar(genes, geneSet): if len(genes) == len(set(genes)): cuenta = random.randint(1, 4) while cuenta > 0: @@ -64,13 +64,13 @@ def fnMostrar(candidato): def fnObtenerAptitud(genes): return obtener_aptitud(genes) - def fnMudar(genes): - mudar(genes, geneSet) + def fnMutar(genes): + mutar(genes, geneSet) aptitudÓptima = Aptitud(36, 360, 0) mejor = genetic.obtener_mejor(fnObtenerAptitud, 10, aptitudÓptima, geneSet, fnMostrar, - mutación_personalizada=fnMudar) + mutación_personalizada=fnMutar) self.assertTrue(not aptitudÓptima > mejor.Aptitud) def test_comparativa(self): diff --git a/es/ch06/genetic.py b/es/ch06/genetic.py index f1c934d..89e92e3 100644 --- a/es/ch06/genetic.py +++ b/es/ch06/genetic.py @@ -30,7 +30,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -40,7 +40,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -50,17 +50,17 @@ def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, mostrar, mutación_personalizada=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) def fnGenerarPadre(): return _generar_padre(longitudObjetivo, geneSet, obtener_aptitud) - for mejora in _obtener_mejoras(fnMudar, fnGenerarPadre): + for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): mostrar(mejora) if not aptitudÓptima > mejora.Aptitud: return mejora diff --git a/es/ch07/caballos.py b/es/ch07/caballos.py index 609f974..b7ee5ee 100644 --- a/es/ch07/caballos.py +++ b/es/ch07/caballos.py @@ -41,7 +41,7 @@ def mostrar(candidato, horaInicio, tableroAncho, tableroAltura): diferencia)) -def mudar(genes, tableroAncho, tableroAltura, todasPosiciones, +def mutar(genes, tableroAncho, tableroAltura, todasPosiciones, posicionesNoBordeadas): cuenta = 2 if random.randint(0, 10) == 0 else 1 while cuenta > 0: @@ -150,8 +150,8 @@ def fnObtenerAptitud(genes): def fnObtenerPosiciónAleatoria(): return random.choice(posicionesNoBordeadas) - def fnMudar(genes): - mudar(genes, tableroAncho, tableroAltura, todasPosiciones, + def fnMutar(genes): + mutar(genes, tableroAncho, tableroAltura, todasPosiciones, posicionesNoBordeadas) def fnCrear(): @@ -159,7 +159,7 @@ def fnCrear(): aptitudÓptima = tableroAncho * tableroAltura mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMudar, fnCrear) + None, fnMostrar, fnMutar, fnCrear) self.assertTrue(not aptitudÓptima > mejor.Aptitud) diff --git a/es/ch07/genetic.py b/es/ch07/genetic.py index da0332e..4d334b1 100644 --- a/es/ch07/genetic.py +++ b/es/ch07/genetic.py @@ -30,7 +30,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -40,7 +40,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -51,11 +51,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, mostrar, mutación_personalizada=None, creación_personalizada=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -66,7 +66,7 @@ def fnGenerarPadre(): genes = creación_personalizada() return Cromosoma(genes, obtener_aptitud(genes)) - for mejora in _obtener_mejoras(fnMudar, fnGenerarPadre): + for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre): mostrar(mejora) if not aptitudÓptima > mejora.Aptitud: return mejora diff --git "a/es/ch08/cuadradosM\303\241gicos.py" "b/es/ch08/cuadradosM\303\241gicos.py" index 0f00a93..4e5d7c7 100644 --- "a/es/ch08/cuadradosM\303\241gicos.py" +++ "b/es/ch08/cuadradosM\303\241gicos.py" @@ -65,7 +65,7 @@ def obtener_sums(genes, tamañoDiagonal): return filas, columnas, sumaDiagonalNoreste, sumaDiagonalSureste -def mudar(genes, índices): +def mutar(genes, índices): índiceA, índiceB = random.sample(índices, 2) genes[índiceA], genes[índiceB] = genes[índiceB], genes[índiceA] @@ -100,8 +100,8 @@ def fnMostrar(candidato): geneÍndices = [i for i in range(0, len(geneSet))] - def fnMudar(genes): - mudar(genes, geneÍndices) + def fnMutar(genes): + mutar(genes, geneÍndices) def fnCreaciónPersonalizada(): return random.sample(geneSet, len(geneSet)) @@ -109,7 +109,7 @@ def fnCreaciónPersonalizada(): valorÓptimo = Aptitud(0) horaInicio = datetime.datetime.now() mejor = genetic.obtener_mejor(fnObtenerAptitud, nCuadrado, valorÓptimo, - geneSet, fnMostrar, fnMudar, + geneSet, fnMostrar, fnMutar, fnCreaciónPersonalizada, edadMáxima) self.assertTrue(not valorÓptimo > mejor.Aptitud) diff --git a/es/ch08/genetic.py b/es/ch08/genetic.py index 0815864..1b78da4 100644 --- a/es/ch08/genetic.py +++ b/es/ch08/genetic.py @@ -32,7 +32,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -42,7 +42,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -53,11 +53,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, mostrar, mutación_personalizada=None, creación_personalizada=None, edadMáxima=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -68,7 +68,7 @@ def fnGenerarPadre(): genes = creación_personalizada() return Cromosoma(genes, obtener_aptitud(genes)) - for mejora in _obtener_mejoras(fnMudar, fnGenerarPadre, edadMáxima): + for mejora in _obtener_mejoras(fnMutar, fnGenerarPadre, edadMáxima): mostrar(mejora) if not aptitudÓptima > mejora.Aptitud: return mejora diff --git a/es/ch09/mochila.py b/es/ch09/mochila.py index 520cf43..e575a5d 100644 --- a/es/ch09/mochila.py +++ b/es/ch09/mochila.py @@ -81,7 +81,7 @@ def añadir(genes, artículos, pesoMáximo, volumenMáximo): cantidadMáxima) if cantidadMáxima > 0 else None -def mudar(genes, artículos, pesoMáximo, volumenMáximo, ventana): +def mutar(genes, artículos, pesoMáximo, volumenMáximo, ventana): ventana.deslizar() aptitud = obtener_aptitud(genes) pesoRestante = pesoMáximo - aptitud.PesoTotal @@ -172,12 +172,12 @@ def fnObtenerAptitud(genes): def fnCrear(): return crear(artículos, pesoMáximo, volumenMáximo) - def fnMudar(genes): - mudar(genes, artículosOrdenados, pesoMáximo, volumenMáximo, + def fnMutar(genes): + mutar(genes, artículosOrdenados, pesoMáximo, volumenMáximo, ventana) mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMudar, fnCrear, + None, fnMostrar, fnMutar, fnCrear, edadMáxima=50) self.assertTrue(not aptitudÓptima > mejor.Aptitud) @@ -267,7 +267,6 @@ def __gt__(self, otro): return self.PesoTotal < otro.PesoTotal return self.VolumenTotal < otro.VolumenTotal - def __str__(self): return "peso: {:0.2f} vol: {:0.2f} valor: {}".format( self.PesoTotal, diff --git a/es/ch10/ecuacionesLineales.py b/es/ch10/ecuacionesLineales.py index 5f0730e..497fcb9 100644 --- a/es/ch10/ecuacionesLineales.py +++ b/es/ch10/ecuacionesLineales.py @@ -40,7 +40,7 @@ def mostrar(candidato, horaInicio, fnGenesAEntradas): diferencia)) -def mudar(genes, geneSetOrdenado, ventana, geneÍndices): +def mutar(genes, geneSetOrdenado, ventana, geneÍndices): índices = random.sample(geneÍndices, random.randint(1, len(genes))) \ if random.randint(0, 10) == 0 else [random.choice(geneÍndices)] ventana.deslizar() @@ -161,13 +161,13 @@ def fnMostrar(candidato): def fnObtenerAptitud(genes): return obtener_aptitud(genes, ecuaciones) - def fnMudar(genes): - mudar(genes, geneSetOrdenado, ventana, geneÍndices) + def fnMutar(genes): + mutar(genes, geneSetOrdenado, ventana, geneÍndices) aptitudÓptima = Aptitud(0) mejor = genetic.obtener_mejor(fnObtenerAptitud, numUnknowns, aptitudÓptima, geneSet, fnMostrar, - fnMudar, edadMáxima=edadMáxima) + fnMutar, edadMáxima=edadMáxima) self.assertTrue(not aptitudÓptima > mejor.Aptitud) diff --git a/es/ch11/sudoku.py b/es/ch11/sudoku.py index 7130e22..1758f68 100644 --- a/es/ch11/sudoku.py +++ b/es/ch11/sudoku.py @@ -52,7 +52,7 @@ def mostrar(candidato, horaInicio): .format(candidato.Aptitud, diferencia)) -def mudar(genes, reglasDeValidación): +def mutar(genes, reglasDeValidación): reglaSeleccionada = next(regla for regla in reglasDeValidación if genes[regla.Índice] == genes[regla.OtroÍndice]) if reglaSeleccionada is None: @@ -99,11 +99,11 @@ def fnObtenerAptitud(genes): def fnCrear(): return random.sample(geneSet * 9, 81) - def fnMudar(genes): - mudar(genes, reglasDeValidación) + def fnMutar(genes): + mutar(genes, reglasDeValidación) mejor = genetic.obtener_mejor(fnObtenerAptitud, None, valorÓptimo, - None, fnMostrar, fnMudar, fnCrear, + None, fnMostrar, fnMutar, fnCrear, edadMáxima=50) self.assertEqual(mejor.Aptitud, valorÓptimo) diff --git a/es/ch12/genetic.py b/es/ch12/genetic.py index 1703276..c9b249e 100644 --- a/es/ch12/genetic.py +++ b/es/ch12/genetic.py @@ -33,7 +33,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud, Estrategias.Creación) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -43,7 +43,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -51,7 +51,7 @@ def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mudar, generar_padre): + mutar, generar_padre): índiceDeDonante = random.randrange(0, len(padres)) if índiceDeDonante == índice: índiceDeDonante = (índiceDeDonante + 1) % len(padres) @@ -59,7 +59,7 @@ def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, if genesDelNiño is None: # padre y donante son indistinguibles padres[índiceDeDonante] = generar_padre() - return mudar(padres[índice]) + return mutar(padres[índice]) aptitud = obtener_aptitud(genesDelNiño) return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) @@ -69,11 +69,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, creación_personalizada=None, edadMáxima=None, tamañoDePiscina=1, intercambiar=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -87,9 +87,9 @@ def fnGenerarPadre(): búsquedaDeEstrategia = { Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMudar(p), + Estrategias.Mutación: lambda p, i, o: fnMutar(p), Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMudar, + _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, fnGenerarPadre) } @@ -101,7 +101,7 @@ def fnNuevoNiño(padre, índice, padres): return random.choice(estrategiasUsadas)(padre, índice, padres) else: def fnNuevoNiño(padre, índice, padres): - return fnMudar(padre) + return fnMutar(padre) for mejora in _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, edadMáxima, tamañoDePiscina): diff --git a/es/ch12/vendedor.py b/es/ch12/vendedor.py index 65ce9cc..138b8b5 100644 --- a/es/ch12/vendedor.py +++ b/es/ch12/vendedor.py @@ -52,7 +52,7 @@ def obtener_distancia(ubicaciónA, ubicaciónB): return ladoC -def mudar(genes, fnObtenerAptitud): +def mutar(genes, fnObtenerAptitud): cuenta = random.randint(2, len(genes)) aptitudInicial = fnObtenerAptitud(genes) while cuenta > 0: @@ -145,8 +145,8 @@ def fnMostrar(candidato): def fnObtenerAptitud(genes): return obtener_aptitud(genes, búsquedaDeUbicación) - def fnMudar(genes): - mudar(genes, fnObtenerAptitud) + def fnMutar(genes): + mutar(genes, fnObtenerAptitud) def fnIntercambio(padre, donante): return intercambiar(padre, donante, fnObtenerAptitud) @@ -154,7 +154,7 @@ def fnIntercambio(padre, donante): aptitudÓptima = fnObtenerAptitud(secuenciaÓptima) horaInicio = datetime.datetime.now() mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMudar, fnCrear, + None, fnMostrar, fnMutar, fnCrear, edadMáxima=500, tamañoDePiscina=25, intercambiar=fnIntercambio) self.assertTrue(not aptitudÓptima > mejor.Aptitud) diff --git a/es/ch13/genetic.py b/es/ch13/genetic.py index e42a1ed..b439082 100644 --- a/es/ch13/genetic.py +++ b/es/ch13/genetic.py @@ -33,7 +33,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud, Estrategias.Creación) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -43,7 +43,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -51,7 +51,7 @@ def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mudar, generar_padre): + mutar, generar_padre): índiceDeDonante = random.randrange(0, len(padres)) if índiceDeDonante == índice: índiceDeDonante = (índiceDeDonante + 1) % len(padres) @@ -59,7 +59,7 @@ def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, if genesDelNiño is None: # padre y donante son indistinguibles padres[índiceDeDonante] = generar_padre() - return mudar(padres[índice]) + return mutar(padres[índice]) aptitud = obtener_aptitud(genesDelNiño) return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) @@ -69,11 +69,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, creación_personalizada=None, edadMáxima=None, tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -87,9 +87,9 @@ def fnGenerarPadre(): búsquedaDeEstrategia = { Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMudar(p), + Estrategias.Mutación: lambda p, i, o: fnMutar(p), Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMudar, + _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, fnGenerarPadre) } @@ -101,7 +101,7 @@ def fnNuevoNiño(padre, índice, padres): return random.choice(estrategiasUsadas)(padre, índice, padres) else: def fnNuevoNiño(padre, índice, padres): - return fnMudar(padre) + return fnMutar(padre) for caducado, mejora in \ _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, edadMáxima, diff --git a/es/ch13/pi.py b/es/ch13/pi.py index b5b5e96..b15cbb0 100644 --- a/es/ch13/pi.py +++ b/es/ch13/pi.py @@ -61,7 +61,7 @@ def obtener_denominador(genes, valoresDeBits): return bits_a_entero(genes[len(valoresDeBits):], valoresDeBits) -def mudar(genes, numBits): +def mutar(genes, numBits): índiceDelNumerador, índiceDelDenominador \ = random.randrange(0, numBits), random.randrange(numBits, len(genes)) @@ -83,13 +83,13 @@ def fnObtenerAptitud(genes): aptitudÓptima = 3.14159 - def fnMudar(genes): - mudar(genes, len(valoresDeBits)) + def fnMutar(genes): + mutar(genes, len(valoresDeBits)) longitud = 2 * len(valoresDeBits) mejor = genetic.obtener_mejor(fnObtenerAptitud, longitud, aptitudÓptima, geneSet, fnMostrar, - fnMudar, edadMáxima=250, + fnMutar, edadMáxima=250, segundosMáximos=segundosMáximos) return aptitudÓptima <= mejor.Aptitud diff --git a/es/ch14/ecuaciones.py b/es/ch14/ecuaciones.py index 3466cc0..ffc76ca 100644 --- a/es/ch14/ecuaciones.py +++ b/es/ch14/ecuaciones.py @@ -81,7 +81,7 @@ def crear(números, operaciones, númerosMin, númerosMax): return genes -def mudar(genes, números, operaciones, númerosMin, númerosMax, +def mutar(genes, números, operaciones, númerosMin, númerosMax, fnObtenerAptitud): cuenta = random.randint(1, 10) aptitudInicial = fnObtenerAptitud(genes) @@ -159,13 +159,13 @@ def fnObtenerAptitud(genes): def fnCrear(): return crear(números, operaciones, númerosMin, númerosMax) - def fnMudar(niño): - mudar(niño, números, operaciones, númerosMin, númerosMax, + def fnMutar(niño): + mutar(niño, números, operaciones, númerosMin, númerosMax, fnObtenerAptitud) aptitudÓptima = fnObtenerAptitud(soluciónDeLongitudÓptima) mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMudar, fnCrear, + None, fnMostrar, fnMutar, fnCrear, edadMáxima=50) self.assertTrue(not aptitudÓptima > mejor.Aptitud) diff --git a/es/ch15/pruebas.py b/es/ch15/pruebas.py index 4a009c4..81e931a 100644 --- a/es/ch15/pruebas.py +++ b/es/ch15/pruebas.py @@ -38,7 +38,7 @@ def mostrar(candidato, horaInicio, fnEvaluar): programa.print() -def mudar(genes, geneSet, mínGenes, máxGenes, fnObtenerAptitud, rondasMáximas): +def mutar(genes, geneSet, mínGenes, máxGenes, fnObtenerAptitud, rondasMáximas): cuenta = random.randint(1, rondasMáximas) aptitudInicial = fnObtenerAptitud(genes) while cuenta > 0: @@ -232,8 +232,8 @@ def fnObtenerAptitud(genes): def fnMostrar(candidato): mostrar(candidato, horaInicio, fnEvaluar) - def fnMudar(niño): - mudar(niño, geneSet, mínGenes, máxGenes, fnObtenerAptitud, + def fnMutar(niño): + mutar(niño, geneSet, mínGenes, máxGenes, fnObtenerAptitud, rondasMáximasDeMutación) aptitudÓptima = Aptitud(anchura * altura, @@ -241,7 +241,7 @@ def fnMudar(niño): númeroEsperadoDePasos) mejor = genetic.obtener_mejor(fnObtenerAptitud, None, aptitudÓptima, - None, fnMostrar, fnMudar, fnCrear, + None, fnMostrar, fnMutar, fnCrear, edadMáxima=None, tamañoDePiscina=10, intercambiar=intercambiar) diff --git a/es/ch16/genetic.py b/es/ch16/genetic.py index 7b4c155..a0af7fc 100644 --- a/es/ch16/genetic.py +++ b/es/ch16/genetic.py @@ -33,7 +33,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud, Estrategias.Creación) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -43,7 +43,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -51,7 +51,7 @@ def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mudar, generar_padre): + mutar, generar_padre): índiceDeDonante = random.randrange(0, len(padres)) if índiceDeDonante == índice: índiceDeDonante = (índiceDeDonante + 1) % len(padres) @@ -59,7 +59,7 @@ def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, if genesDelNiño is None: # padre y donante son indistinguibles padres[índiceDeDonante] = generar_padre() - return mudar(padres[índice]) + return mutar(padres[índice]) aptitud = obtener_aptitud(genesDelNiño) return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) @@ -69,11 +69,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, creación_personalizada=None, edadMáxima=None, tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -87,9 +87,9 @@ def fnGenerarPadre(): búsquedaDeEstrategia = { Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMudar(p), + Estrategias.Mutación: lambda p, i, o: fnMutar(p), Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMudar, + _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, fnGenerarPadre) } @@ -101,7 +101,7 @@ def fnNuevoNiño(padre, índice, padres): return random.choice(estrategiasUsadas)(padre, índice, padres) else: def fnNuevoNiño(padre, índice, padres): - return fnMudar(padre) + return fnMutar(padre) for caducado, mejora in _obtener_mejoras(fnNuevoNiño, fnGenerarPadre, edadMáxima, tamañoDePiscina, diff --git a/es/ch16/pruebas.py b/es/ch16/pruebas.py index fd3540a..d11f6a8 100644 --- a/es/ch16/pruebas.py +++ b/es/ch16/pruebas.py @@ -60,7 +60,7 @@ def crear_gen(índice, puertas, fuentes): return Nodo(tipoDePuerta[0], índiceA, índiceB) -def mudar(genesDelNiño, fnCrearGen, fnObtenerAptitud, fuenteCount): +def mutar(genesDelNiño, fnCrearGen, fnObtenerAptitud, fuenteCount): cuenta = random.randint(1, 5) aptitudInicial = fnObtenerAptitud(genesDelNiño) while cuenta > 0: @@ -173,8 +173,8 @@ def fnObtenerAptitud(genes): def fnCrearGen(índice): return crear_gen(índice, self.puertas, self.fuentes) - def fnMudar(genes): - mudar(genes, fnCrearGen, fnObtenerAptitud, len(self.fuentes)) + def fnMutar(genes): + mutar(genes, fnCrearGen, fnObtenerAptitud, len(self.fuentes)) longitudMáxima = 50 @@ -186,7 +186,7 @@ def fnFunciónDeOptimización(longitudVariable): longitudMáxima = longitudVariable return genetic.obtener_mejor( fnObtenerAptitud, None, len(reglas), None, fnMostrar, - fnMudar, fnCrear, tamañoDePiscina=3, segundosMáximos=30) + fnMutar, fnCrear, tamañoDePiscina=3, segundosMáximos=30) def fnEsUnaMejora(mejorActual, niño): return niño.Aptitud == len(reglas) and \ diff --git a/es/ch17/regex.py b/es/ch17/regex.py index fe8aa50..f29d61f 100644 --- a/es/ch17/regex.py +++ b/es/ch17/regex.py @@ -131,13 +131,13 @@ def mostrar(candidato, horaInicio): reparar_regex(candidato.Genes), candidato.Aptitud, diferencia)) -def mudar_añadir(genes, geneSet): +def mutar_añadir(genes, geneSet): índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 genes[índice:índice] = [random.choice(geneSet)] return True -def mudar_remover(genes): +def mutar_remover(genes): if len(genes) < 1: return False del genes[random.randrange(0, len(genes))] @@ -146,7 +146,7 @@ def mudar_remover(genes): return True -def mudar_reemplazar(genes, geneSet): +def mutar_reemplazar(genes, geneSet): if len(genes) < 1: return False índice = random.randrange(0, len(genes)) @@ -154,7 +154,7 @@ def mudar_reemplazar(genes, geneSet): return True -def mudar_intercambiar(genes): +def mutar_intercambiar(genes): if len(genes) < 2: return False índiceA, índiceB = random.sample(range(len(genes)), 2) @@ -162,7 +162,7 @@ def mudar_intercambiar(genes): return True -def mudar_mover(genes): +def mutar_mover(genes): if len(genes) < 3: return False principio = random.choice(range(len(genes))) @@ -176,7 +176,7 @@ def mudar_mover(genes): return True -def mudar_a_conjunto_de_caracteres(genes): +def mutar_a_conjunto_de_caracteres(genes): if len(genes) < 3: return False o = [i for i in range(1, len(genes) - 1) @@ -197,7 +197,7 @@ def mudar_a_conjunto_de_caracteres(genes): return True -def mudar_a_conjunto_de_caracteres_izquierda(genes, deseadas): +def mutar_a_conjunto_de_caracteres_izquierda(genes, deseadas): if len(genes) < 4: return False o = [i for i in range(-1, len(genes) - 3) @@ -225,13 +225,13 @@ def mudar_a_conjunto_de_caracteres_izquierda(genes, deseadas): return True -def mudar_add_deseadas(genes, deseadas): +def mutar_add_deseadas(genes, deseadas): índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 genes[índice:índice] = ['|'] + [random.choice(deseadas)] return True -def mudar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): +def mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): aptitudInicial = fnObtenerAptitud(genes) cuenta = random.choice(recuentoDeMutaciones) for i in range(1, cuenta + 2): @@ -262,7 +262,7 @@ def test_códigos_de_estado(self): noDeseadas = {"N" + l for l in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" if "N" + l not in deseadas} operadoresPersonalizados = [ - partial(mudar_a_conjunto_de_caracteres_izquierda, + partial(mutar_a_conjunto_de_caracteres_izquierda, deseadas=deseadas), ] self.encontrar_regex(deseadas, noDeseadas, 11, @@ -275,7 +275,7 @@ def test_longitud_par(self): noDeseadas = {"0", "1", "000", "001", "010", "011", "100", "101", "110", "111", ""} operadoresPersonalizados = [ - mudar_a_conjunto_de_caracteres, + mutar_a_conjunto_de_caracteres, ] self.encontrar_regex(deseadas, noDeseadas, 10, operadoresPersonalizados) @@ -297,10 +297,10 @@ def test_50_códigos_de_estado(self): if a + b not in deseadas} | \ set(i for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") operadoresPersonalizados = [ - partial(mudar_a_conjunto_de_caracteres_izquierda, + partial(mutar_a_conjunto_de_caracteres_izquierda, deseadas=deseadas), - mudar_a_conjunto_de_caracteres, - partial(mudar_add_deseadas, deseadas=[i for i in deseadas]), + mutar_a_conjunto_de_caracteres, + partial(mutar_add_deseadas, deseadas=[i for i in deseadas]), ] self.encontrar_regex(deseadas, noDeseadas, 120, operadoresPersonalizados) @@ -320,17 +320,17 @@ def fnObtenerAptitud(genes): recuentoDeMutaciones = [1] operadoresDeMutación = [ - partial(mudar_añadir, geneSet=geneSet), - partial(mudar_reemplazar, geneSet=geneSet), - mudar_remover, - mudar_intercambiar, - mudar_mover, + partial(mutar_añadir, geneSet=geneSet), + partial(mutar_reemplazar, geneSet=geneSet), + mutar_remover, + mutar_intercambiar, + mutar_mover, ] if operadoresPersonalizados is not None: operadoresDeMutación.extend(operadoresPersonalizados) - def fnMudar(genes): - mudar(genes, fnObtenerAptitud, operadoresDeMutación, + def fnMutar(genes): + mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones) aptitudÓptima = Aptitud(len(deseadas), len(deseadas), 0, @@ -338,7 +338,7 @@ def fnMudar(genes): mejor = genetic.obtener_mejor( fnObtenerAptitud, max(len(i) for i in genesDeTexto), - aptitudÓptima, geneSet, fnMostrar, fnMudar, tamañoDePiscina=10) + aptitudÓptima, geneSet, fnMostrar, fnMutar, tamañoDePiscina=10) self.assertTrue(not aptitudÓptima > mejor.Aptitud) for info in erroresEnRegexes.values(): @@ -381,7 +381,7 @@ def __gt__(self, otro): return self.Longitud < otro.Longitud def __str__(self): - return "coincide con: {} deseadas y, {} no deseadas, lon {}".format( + return "coincide con: {} deseadas, y {} no deseadas, lon {}".format( "todas" if self._totalDeseado == self.NúmeroDeDeseadosQueCoincidieron else self.NúmeroDeDeseadosQueCoincidieron, diff --git a/es/ch18/genetic.py b/es/ch18/genetic.py index 5915205..321ca6d 100644 --- a/es/ch18/genetic.py +++ b/es/ch18/genetic.py @@ -34,7 +34,7 @@ def _generar_padre(longitud, geneSet, obtener_aptitud): return Cromosoma(genes, aptitud, Estrategias.Creación) -def _mudar(padre, geneSet, obtener_aptitud): +def _mutar(padre, geneSet, obtener_aptitud): genesDelNiño = padre.Genes[:] índice = random.randrange(0, len(padre.Genes)) nuevoGen, alterno = random.sample(geneSet, 2) @@ -44,7 +44,7 @@ def _mudar(padre, geneSet, obtener_aptitud): return Cromosoma(genesDelNiño, aptitud, Estrategias.Mutación) -def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): +def _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud): genesDelNiño = padre.Genes[:] mutación_personalizada(genesDelNiño) aptitud = obtener_aptitud(genesDelNiño) @@ -52,7 +52,7 @@ def _mudar_personalizada(padre, mutación_personalizada, obtener_aptitud): def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, - mudar, generar_padre): + mutar, generar_padre): índiceDeDonante = random.randrange(0, len(padres)) if índiceDeDonante == índice: índiceDeDonante = (índiceDeDonante + 1) % len(padres) @@ -60,7 +60,7 @@ def _intercambiar(genesDePadre, índice, padres, obtener_aptitud, intercambiar, if genesDelNiño is None: # padre y donante son indistinguibles padres[índiceDeDonante] = generar_padre() - return mudar(padres[índice]) + return mutar(padres[índice]) aptitud = obtener_aptitud(genesDelNiño) return Cromosoma(genesDelNiño, aptitud, Estrategias.Intercambio) @@ -70,11 +70,11 @@ def obtener_mejor(obtener_aptitud, longitudObjetivo, aptitudÓptima, geneSet, creación_personalizada=None, edadMáxima=None, tamañoDePiscina=1, intercambiar=None, segundosMáximos=None): if mutación_personalizada is None: - def fnMudar(padre): - return _mudar(padre, geneSet, obtener_aptitud) + def fnMutar(padre): + return _mutar(padre, geneSet, obtener_aptitud) else: - def fnMudar(padre): - return _mudar_personalizada(padre, mutación_personalizada, + def fnMutar(padre): + return _mutar_personalizada(padre, mutación_personalizada, obtener_aptitud) if creación_personalizada is None: @@ -88,9 +88,9 @@ def fnGenerarPadre(): búsquedaDeEstrategia = { Estrategias.Creación: lambda p, i, o: fnGenerarPadre(), - Estrategias.Mutación: lambda p, i, o: fnMudar(p), + Estrategias.Mutación: lambda p, i, o: fnMutar(p), Estrategias.Intercambio: lambda p, i, o: - _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMudar, + _intercambiar(p.Genes, i, o, obtener_aptitud, intercambiar, fnMutar, fnGenerarPadre) } @@ -102,7 +102,7 @@ def fnNuevoNiño(padre, índice, padres): return random.choice(estrategiasUsadas)(padre, índice, padres) else: def fnNuevoNiño(padre, índice, padres): - return fnMudar(padre) + return fnMutar(padre) for caducado, mejora in _obtener_mejoras( fnNuevoNiño, fnGenerarPadre, edadMáxima, tamañoDePiscina, diff --git a/es/ch18/ticTacToe.py b/es/ch18/ticTacToe.py index 4b3ce0d..eb8ea4a 100644 --- a/es/ch18/ticTacToe.py +++ b/es/ch18/ticTacToe.py @@ -161,13 +161,13 @@ def mostrar(candidato, horaInicio): diferencia)) -def mudar_añadir(genes, geneSet): +def mutar_añadir(genes, geneSet): índice = random.randrange(0, len(genes) + 1) if len(genes) > 0 else 0 genes[índice:índice] = [random.choice(geneSet)] return True -def mudar_remover(genes): +def mutar_remover(genes): if len(genes) < 1: return False del genes[random.randrange(0, len(genes))] @@ -176,7 +176,7 @@ def mudar_remover(genes): return True -def mudar_reemplazar(genes, geneSet): +def mutar_reemplazar(genes, geneSet): if len(genes) < 1: return False índice = random.randrange(0, len(genes)) @@ -184,7 +184,7 @@ def mudar_reemplazar(genes, geneSet): return True -def mudar_intercambiar_adyacente(genes): +def mutar_intercambiar_adyacente(genes): if len(genes) < 2: return False índice = random.choice(range(len(genes) - 1)) @@ -192,7 +192,7 @@ def mudar_intercambiar_adyacente(genes): return True -def mudar_mover(genes): +def mutar_mover(genes): if len(genes) < 3: return False principio = random.choice(range(len(genes))) @@ -206,7 +206,7 @@ def mudar_mover(genes): return True -def mudar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): +def mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones): aptitudInicial = fnObtenerAptitud(genes) cuenta = random.choice(recuentoDeMutaciones) for i in range(1, cuenta + 2): @@ -276,20 +276,20 @@ def fnObtenerAptitud(genes): recuentoDeMutaciones = [1] operadoresDeMutación = [ - partial(mudar_añadir, geneSet=geneSet), - partial(mudar_reemplazar, geneSet=geneSet), - mudar_remover, - mudar_intercambiar_adyacente, - mudar_mover, + partial(mutar_añadir, geneSet=geneSet), + partial(mutar_reemplazar, geneSet=geneSet), + mutar_remover, + mutar_intercambiar_adyacente, + mutar_mover, ] - def fnMudar(genes): - mudar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones) + def fnMutar(genes): + mutar(genes, fnObtenerAptitud, operadoresDeMutación, recuentoDeMutaciones) def fnIntercambio(padre, donante): niño = padre[0:int(len(padre) / 2)] + \ donante[int(len(donante) / 2):] - fnMudar(niño) + fnMutar(niño) return niño def fnCrear(): @@ -297,7 +297,7 @@ def fnCrear(): aptitudÓptima = Aptitud(620, 120, 0, 11) mejor = genetic.obtener_mejor(fnObtenerAptitud, mínGenes, aptitudÓptima, None, - fnMostrar, fnMudar, fnCrear, edadMáxima=500, + fnMostrar, fnMutar, fnCrear, edadMáxima=500, tamañoDePiscina=20, intercambiar=fnIntercambio) self.assertTrue(not aptitudÓptima > mejor.Aptitud) @@ -316,20 +316,20 @@ def fnMostrar(genes, ganados, empates, perdidos, generación): recuentoDeMutaciones = [1] operadoresDeMutación = [ - partial(mudar_añadir, geneSet=geneSet), - partial(mudar_reemplazar, geneSet=geneSet), - mudar_remover, - mudar_intercambiar_adyacente, - mudar_mover, + partial(mutar_añadir, geneSet=geneSet), + partial(mutar_reemplazar, geneSet=geneSet), + mutar_remover, + mutar_intercambiar_adyacente, + mutar_mover, ] - def fnMudar(genes): - mudar(genes, lambda x: 0, operadoresDeMutación, recuentoDeMutaciones) + def fnMutar(genes): + mutar(genes, lambda x: 0, operadoresDeMutación, recuentoDeMutaciones) def fnIntercambio(padre, donante): niño = padre[0:int(len(padre) / 2)] + \ donante[int(len(donante) / 2):] - fnMudar(niño) + fnMutar(niño) return niño def fnCrear(): From 6e0d2416e070f22a35c1650834d80ce6381e6c2b Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Thu, 2 May 2019 17:16:34 -0500 Subject: [PATCH 14/19] fix inefficiency reported by Piotr.Lewczuk@uk-erlangen.de --- ch08/genetic.py | 3 +-- ch12/genetic.py | 3 +-- ch13/genetic.py | 3 +-- ch16/genetic.py | 3 +-- ch18/genetic.py | 3 +-- es/ch08/genetic.py | 3 +-- es/ch12/genetic.py | 3 +-- es/ch13/genetic.py | 3 +-- es/ch15/genetic.py | 3 +-- es/ch16/genetic.py | 3 +-- es/ch18/genetic.py | 3 +-- 11 files changed, 11 insertions(+), 22 deletions(-) diff --git a/ch08/genetic.py b/ch08/genetic.py index 875bbd7..189107d 100644 --- a/ch08/genetic.py +++ b/ch08/genetic.py @@ -85,8 +85,7 @@ def _get_improvement(new_child, generate_parent, maxAge): continue index = bisect_left(historicalFitnesses, child.Fitness, 0, len(historicalFitnesses)) - difference = len(historicalFitnesses) - index - proportionSimilar = difference / len(historicalFitnesses) + proportionSimilar = index / len(historicalFitnesses) if random.random() < exp(-proportionSimilar): parent = child continue diff --git a/ch12/genetic.py b/ch12/genetic.py index dc5c89c..5ee0ea9 100644 --- a/ch12/genetic.py +++ b/ch12/genetic.py @@ -134,8 +134,7 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize): continue index = bisect_left(historicalFitnesses, child.Fitness, 0, len(historicalFitnesses)) - difference = len(historicalFitnesses) - index - proportionSimilar = difference / len(historicalFitnesses) + proportionSimilar = index / len(historicalFitnesses) if random.random() < exp(-proportionSimilar): parents[pindex] = child continue diff --git a/ch13/genetic.py b/ch13/genetic.py index d040846..550b7c2 100644 --- a/ch13/genetic.py +++ b/ch13/genetic.py @@ -143,8 +143,7 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, maxSeconds): continue index = bisect_left(historicalFitnesses, child.Fitness, 0, len(historicalFitnesses)) - difference = len(historicalFitnesses) - index - proportionSimilar = difference / len(historicalFitnesses) + proportionSimilar = index / len(historicalFitnesses) if random.random() < exp(-proportionSimilar): parents[pindex] = child continue diff --git a/ch16/genetic.py b/ch16/genetic.py index 16a9841..99c9a3b 100644 --- a/ch16/genetic.py +++ b/ch16/genetic.py @@ -144,8 +144,7 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, continue index = bisect_left(historicalFitnesses, child.Fitness, 0, len(historicalFitnesses)) - difference = len(historicalFitnesses) - index - proportionSimilar = difference / len(historicalFitnesses) + proportionSimilar = index / len(historicalFitnesses) if random.random() < exp(-proportionSimilar): parents[pindex] = child continue diff --git a/ch18/genetic.py b/ch18/genetic.py index 7c6d815..01a29de 100644 --- a/ch18/genetic.py +++ b/ch18/genetic.py @@ -145,8 +145,7 @@ def _get_improvement(new_child, generate_parent, maxAge, poolSize, continue index = bisect_left(historicalFitnesses, child.Fitness, 0, len(historicalFitnesses)) - difference = len(historicalFitnesses) - index - proportionSimilar = difference / len(historicalFitnesses) + proportionSimilar = index / len(historicalFitnesses) if random.random() < exp(-proportionSimilar): parents[pindex] = child continue diff --git a/es/ch08/genetic.py b/es/ch08/genetic.py index 1b78da4..059d452 100644 --- a/es/ch08/genetic.py +++ b/es/ch08/genetic.py @@ -88,8 +88,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima): continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padre = niño continue diff --git a/es/ch12/genetic.py b/es/ch12/genetic.py index c9b249e..d564f8b 100644 --- a/es/ch12/genetic.py +++ b/es/ch12/genetic.py @@ -138,8 +138,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina): continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue diff --git a/es/ch13/genetic.py b/es/ch13/genetic.py index b439082..3591c1c 100644 --- a/es/ch13/genetic.py +++ b/es/ch13/genetic.py @@ -150,8 +150,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue diff --git a/es/ch15/genetic.py b/es/ch15/genetic.py index 6a00549..9659892 100644 --- a/es/ch15/genetic.py +++ b/es/ch15/genetic.py @@ -150,8 +150,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue diff --git a/es/ch16/genetic.py b/es/ch16/genetic.py index a0af7fc..e912871 100644 --- a/es/ch16/genetic.py +++ b/es/ch16/genetic.py @@ -150,8 +150,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue diff --git a/es/ch18/genetic.py b/es/ch18/genetic.py index 321ca6d..4d7506b 100644 --- a/es/ch18/genetic.py +++ b/es/ch18/genetic.py @@ -151,8 +151,7 @@ def _obtener_mejoras(nuevo_niño, generar_padre, edadMáxima, tamañoDePiscina, continue índice = bisect_left(aptitudesHistóricas, niño.Aptitud, 0, len(aptitudesHistóricas)) - diferencia = len(aptitudesHistóricas) - índice - proporciónSimilar = diferencia / len(aptitudesHistóricas) + proporciónSimilar = índice / len(aptitudesHistóricas) if random.random() < exp(-proporciónSimilar): padres[pÍndice] = niño continue From 514b80b44b98df34457e564989598811d986c567 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Fri, 31 May 2019 18:23:52 -0500 Subject: [PATCH 15/19] fix tabs vs spaces in merged code segment reported by Piotr.Lewczuk@uk-erlangen.de --- ch09/knapsackTests.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ch09/knapsackTests.py b/ch09/knapsackTests.py index b589088..a1c1e53 100644 --- a/ch09/knapsackTests.py +++ b/ch09/knapsackTests.py @@ -255,8 +255,8 @@ def __init__(self, totalWeight, totalVolume, totalValue): def __gt__(self, other): if self.TotalValue != other.TotalValue: return self.TotalValue > other.TotalValue - if self.TotalWeight != other.TotalWeight: - return self.TotalWeight < other.TotalWeight + if self.TotalWeight != other.TotalWeight: + return self.TotalWeight < other.TotalWeight return self.TotalValue < other.TotalValue def __str__(self): From 322eda59dc9f0acf2e145abaf82fef7dbed7d556 Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Fri, 31 May 2019 19:13:47 -0500 Subject: [PATCH 16/19] change knapsack Fitness to compare Volume last --- ch09/knapsackTests.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ch09/knapsackTests.py b/ch09/knapsackTests.py index a1c1e53..2f7ac5f 100644 --- a/ch09/knapsackTests.py +++ b/ch09/knapsackTests.py @@ -254,10 +254,10 @@ def __init__(self, totalWeight, totalVolume, totalValue): def __gt__(self, other): if self.TotalValue != other.TotalValue: - return self.TotalValue > other.TotalValue + return self.TotalValue > other.TotalValue if self.TotalWeight != other.TotalWeight: return self.TotalWeight < other.TotalWeight - return self.TotalValue < other.TotalValue + return self.TotalVolume < other.TotalVolume def __str__(self): return "wt: {:0.2f} vol: {:0.2f} value: {}".format( From 2a71f2882b0ecad1ba692d3bf9bc74ce9d02b37d Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Fri, 21 Jun 2019 08:58:22 -0500 Subject: [PATCH 17/19] prevent FutureWarning about || inside a [..] regex --- ch17/regexTests.py | 2 ++ es/ch17/regex.py | 2 ++ 2 files changed, 4 insertions(+) diff --git a/ch17/regexTests.py b/ch17/regexTests.py index 39d654d..63bc94b 100644 --- a/ch17/regexTests.py +++ b/ch17/regexTests.py @@ -96,6 +96,8 @@ def repair_in_character_set(token, result, finals): return repair_ignore_repeat_metas_following_repeat_or_start_metas elif token == '[': pass + elif token == '|' and result[-1] == '|': + pass # suppresses FutureWarning about || else: result.append(token) return repair_in_character_set diff --git a/es/ch17/regex.py b/es/ch17/regex.py index f29d61f..8e5cd61 100644 --- a/es/ch17/regex.py +++ b/es/ch17/regex.py @@ -95,6 +95,8 @@ def reparar_in_character_set(símbolo, resultado, finales): return manejar_metas_de_repetición_que_siguen_metas_de_repetición_o_inicio elif símbolo == '[': pass + elif símbolo == '|' and resultado[-1] == '|': + pass # suprimir FutureWarning sobre || else: resultado.append(símbolo) return reparar_in_character_set From 565e405ad0df8d3c360cfc9c335dbacfcc3041c0 Mon Sep 17 00:00:00 2001 From: ErfanThinker Date: Sat, 4 Jul 2020 11:32:32 +0430 Subject: [PATCH 18/19] Removed redundant condition --- ch16/circuitTests.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ch16/circuitTests.py b/ch16/circuitTests.py index 5e139b6..1f53295 100644 --- a/ch16/circuitTests.py +++ b/ch16/circuitTests.py @@ -53,8 +53,7 @@ def create_gene(index, gates, sources): if gateType[1].input_count() > 0: indexA = random.randint(0, index) if gateType[1].input_count() > 1: - indexB = random.randint(0, index) \ - if index > 1 and index >= len(sources) else 0 + indexB = random.randint(0, index) if indexB == indexA: indexB = random.randint(0, index) return Node(gateType[0], indexA, indexB) From 2359440659559fae56b156fe30320b5f5f9a77ee Mon Sep 17 00:00:00 2001 From: handcraftsman Date: Tue, 7 Jul 2020 07:36:56 -0500 Subject: [PATCH 19/19] make ErfanThinker's change in the Spanish version --- es/ch16/pruebas.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/es/ch16/pruebas.py b/es/ch16/pruebas.py index d11f6a8..03a1a8d 100644 --- a/es/ch16/pruebas.py +++ b/es/ch16/pruebas.py @@ -53,8 +53,7 @@ def crear_gen(índice, puertas, fuentes): if tipoDePuerta[1].recuento_de_entradas() > 0: índiceA = random.randint(0, índice) if tipoDePuerta[1].recuento_de_entradas() > 1: - índiceB = random.randint(0, índice) \ - if índice > 1 and índice >= len(fuentes) else 0 + índiceB = random.randint(0, índice) if índiceB == índiceA: índiceB = random.randint(0, índice) return Nodo(tipoDePuerta[0], índiceA, índiceB)