The following code, which I am trying to run and the value of var_pg is showing 0. The question is that why is it showing 0 whereas the fitness function is returning some value which is greater than 0?
def main(): pop = {0,1,2,4,3,5} var_pg = find_best(pop) print('value of var_pg',var_pg)
def find_best(pop): var_pg = None for p in pop: if (not var_pg) or (var_pg.fitness()>p.fitness()): var_pg=p return var_pg
class CP: def fitness(self): c = 0.1*(5/41) self.__fitness = c return self.__fitness
main()Can somebody please tell me what's am I doing wrong here?
62 Answers
At the first iteration of for p in pop, p is assigned to 0. not var_pg is thus True, so var_pg is assigned to 0 and returned, terminating the loop.
return var_pgshould likely go outside theforloop- The arguments passed in
popare just integers, notCPobjects, so they have nofitness()method.
Because return var_pg is inside the loop and unconditional, the find_best() function will always return the first elements it gets from pop. since pop is a set it could be any of the values. It just happens to be zero in this case.