Projets : structure par projet (jeu_de_la_vie, labyrinthe, mastermind, wator)
This commit is contained in:
85
Projets/src/problem_4.py
Normal file
85
Projets/src/problem_4.py
Normal file
@@ -0,0 +1,85 @@
|
||||
from problem_interface import *
|
||||
from ville import *
|
||||
|
||||
class Problem_4(Problem_Interface) :
|
||||
"""
|
||||
classe probleme n°4 : TSP
|
||||
"""
|
||||
|
||||
def __init__(self, villes):
|
||||
self.__size = len(villes)
|
||||
self.__villes = villes
|
||||
|
||||
|
||||
|
||||
def create_individual(self):
|
||||
'''
|
||||
create a randomly generated indidivual for this problem
|
||||
|
||||
:return: a randomly generated individual gfor this problem
|
||||
:rtype: an Individual object
|
||||
'''
|
||||
return Ville(self.__villes)
|
||||
|
||||
def evaluate_fitness(self, individual):
|
||||
'''
|
||||
compute the fitness of individual for this problem
|
||||
|
||||
:param individual: the individual to consider
|
||||
:type individual: an Individual object
|
||||
:return: the fitness of individual for this problem
|
||||
:rtype: an Individual object
|
||||
'''
|
||||
|
||||
return individual.distance_totale()
|
||||
|
||||
# return sum([1 if mot[letter]==cherche[letter] else 0 for letter in range(len(mot))])
|
||||
|
||||
|
||||
def sort_population(self, population):
|
||||
'''
|
||||
sort population from best fitted to worst fitted individuals.
|
||||
Depending on the problem, it can correspond to ascending or descending order with respect to the fitness function.
|
||||
|
||||
side effect : population is modified by this method
|
||||
|
||||
:param population: the list of individuals to sort
|
||||
:type population: list(Individual)
|
||||
'''
|
||||
population.sort(key = lambda x: x.get_score())
|
||||
|
||||
def best_individual(self, population):
|
||||
'''
|
||||
return the best fitted individual from population.
|
||||
Depending on the problem, it can correspond to the individual with the highest or the lowest fitness value.
|
||||
|
||||
|
||||
:param population: the list of individuals to sort
|
||||
:type population: list(Individual)
|
||||
:return: the best fitted individual of population
|
||||
:rtype: an Individual object
|
||||
'''
|
||||
self.sort_population(population)
|
||||
return population[len(population) -1 ]
|
||||
|
||||
def tournament(self, first, second):
|
||||
'''
|
||||
perform a rounament between two individuals, the winner is the most fitted one, it is returned
|
||||
|
||||
|
||||
:param first: an individual
|
||||
:type first: an Indivdual object
|
||||
:param second: an individual
|
||||
:type second: an Individual object
|
||||
:return: the winner of the tournament
|
||||
:rtype: Individual object
|
||||
'''
|
||||
if first.get_score() < second.get_score():
|
||||
res = first
|
||||
else:
|
||||
res = second
|
||||
return res
|
||||
|
||||
return first if first.get_score() < second.get_score() else second
|
||||
|
||||
|
||||
Reference in New Issue
Block a user