TypeError: ‘int’ object is not subscriptable Genetic Algorithm with search

I have this code which I’m trying to do a local search with genetic algorithm. I wanna use this data to run through :

[0 : [3,2,1],
 1 : [4],
 2 : [6,5],
 3 : [7],
 4 : [8],
 5 : [9]]

The idea is to be equal this graph (but with numbers instead of letters): enter image description here

This is the code I have:

import random

stringSize = 4
top = 10 * stringSize

def value(s):
  return max(-abs(round(0.3*top) - s), .025 - abs(round(0.8 * top) - s))

def ga(times = 10, popSize = 20, mutation_prob = 0.001):
  #population = [int(random.random() * top) for j in range(popSize)]
  population = [0[3,2,1],
                1[4],
                2[6,5],
                3[7],
                4[8],
                5[9]]
  print(len(population))
  print("---")
  history = []
  for i in range(times):
    fitness = [value(population[j]) for j in range(popSize)]
    fitMax = -float('inf')
    
    for j in range(popSize):
      if fitness[j] > fitMax:
        fitMax = fitness[j]
        jBest = j
    history.append(population[jBest])
    fit_sum = sum(fitness)
    probs = [x/fit_sum for x in fitness]
    cutoff = [sum(probs[:j+1]) for j in range(popSize)]
    children = []

    for j in range(popSize):
      r = random.random()
      for k in range(popSize):
        if r < cutoff[k]:
          break
      par1 = population[k-1]
      par2 = population[int(random.random() * popSize)]
      split = int(random.random() * (stringSize + 1))
      child = str(par1)[:split] + str(par2)[split:]
      if random.random() < mutation_prob:
        where = int(random.random() * stringSize)
        what = str(int(random.random() * 10))
        child = child[0:where] + what + child[where + 1:]
      children.append(int(child))
    population = children
  return population

But running it throws this error :

TypeError                                 Traceback (most recent call last)
<ipython-input-34-73e983c9ab93> in <module>()
----> 1 ga()

<ipython-input-33-a504bbf614a5> in ga(times, popSize, mutation_prob)
      4 def ga(times = 10, popSize = 20, mutation_prob = 0.001):
      5   #population = [int(random.random() * top) for j in range(popSize)]
----> 6   population = [0[3,2,1],
      7                 1[4],
      8                 2[6,5],

TypeError: 'int' object is not subscriptable

What can I do to perform it? Am I do it right?

Answer

Your array has a semantic error. E.g. 1[2] is not valid python. If what you want to do is to map a number to an array of numbers, use a dictionary that indexes each list by key or an array of dictionaries with value and children attributes.

As other already pointed out, you could use a dictionary like this:

population = {
   0: [1,2],
   1: [3,4,5],
   ...
}

That error you got usually means you’re trying to index an object that cannot be indexed.

Leave a Reply

Your email address will not be published. Required fields are marked *