Jess
Jess

Reputation: 9

Assigned values have not the same length - Python

I am working on Genetic Algorithm, particularly finding the fitness of population. But it has the #TypeError: object of type 'int' has no len()

Python suggests me a reference code:

/usr/local/lib/python3.9/dist-packages/deap/base.py in setValues(self, values)
186 
187     def setValues(self, values):
188         assert len(values) == len(self.weights), "Assigned values have not the same length than fitness weights"                                                
189         try:
190             self.wvalues = tuple(map(mul, values, self.weights))

TypeError: object of type 'int' has no len()

Below is my original code to find the fitness of population. How can I correct the error by applying the suggested code?

fitness_set = list(tb.map(tb.evaluate, population))
for ind, fit in zip(population, fitness_set):
    ind.fitness.values = fit

Upvotes: 0

Views: 860

Answers (2)

Brian
Brian

Reputation: 13593

I guess that your tb.evaluate function returns an int variable instead of a tuple variable.

I mean if your tb.evaluate function executes something like return 123 in the end, you should change it to return 123,.

This makes the function return a tuple rather then an int.

Returning a tuple variable can solve the problem you encountered because len((123,)) is equal to 1.

len((123,)) doesn't raise an object of type 'int' has no len() error.

Upvotes: 1

Caridorc
Caridorc

Reputation: 6661

TypeError: object of type 'int' has no len()

Means that you are using the function len that is used to get the length of a sequence, on an integral number, this makes no sense so the program fails.

To fix this ind.fitness.values should be a list rather than an integer.

Upvotes: 0

Related Questions