Can we call method using a variable if variable is none?

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?

6

2 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_pg should likely go outside the for loop
  • The arguments passed in pop are just integers, not CP objects, so they have no fitness() 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like