I'm using genetic algorithm for knapsack problem and when I wanted to debug it says : int' object is not subscriptable
it just pointed this 3 spots in the code and in the end it just said this is the error, also it referenced the first error in the fitness def twice
import random
value = [20, 30, 40, 50, 90, 5, 250, 100]
weight = [5, 10, 50, 25, 36, 71, 61, 48,]
inventory = 100
popSize = 10
gens = 100
mutationRate = 0.1
numberOfItems = len(value)
def fitness(individual):
---> totalval = sum(value[i] for i in range(numberOfItems)if individual[i] == 1)
totalW = sum(weight[i] for i in range(numberOfItems)if individual[i] == 1)
if totalW > inventory :
return 0
else :
return totalval
def createItem() :
return[random.randint(0,1) for i in range(numberOfItems)]
def createPop() :
return[random.randint(0,1) for i in range(popSize)]
def selection(pop) :
players = random.sample(pop, 3)
---> players.sort(key = fitness, reverse=True)
return players[0]
def crossover(parent1, parent2) :
point = random.randint(0, numberOfItems-1)
child = parent1[:point] + parent2[point:]
return child
def mutation(individual) :
for i in range(numberOfItems) :
if random.random() < mutationRate:
individual[i] = 1 - individual[i]
pop = createPop()
for i in range(gens) :
newPop = []
for gens in range(popSize) :
---> parent1 = selection(pop)
parent2 = selection(pop)
child = crossover(parent1, parent2)
mutation(child)
newPop.append(child)
pop = newPop
bestInd = max(pop, key=fitness)
bestVal = fitness(bestInd)
bestWei = sum(weight[i] for i in range(numberOfItems) if bestInd[i] == 1 )
print("Best solution is ", bestInd)
print("total value is ", bestVal)
print("total weight is ", bestWei)
what is the problem ?
fitness()is an integer. Your code implies that it should be some subscriptable type (e.g., list, tuple)