python - IndexError:字符串索引超出范围。局部搜索的遗传算法
问题描述
population
我有这段代码,目的是使用遗传算法在变量中执行局部搜索:
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):
print(len(population[i]))
print(i)
print("above")
fitness = [value(population[j][i]) for j in range(len(population[i]))]
fitMax = -float('inf')
for j in range(len(population[i])):
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(len(population[i]))]
children = []
for j in range(len(population[i])):
r = random.random()
for k in range(len(population[i])):
if r < cutoff[k]:
break
print(population[k-1])
print("above2")
par1 = population[k-1]
par2 = population[int(random.random() * len(population[i]))]
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(child[i])
population = children
return population
但是运行这个,它会抛出这个错误:
6
---
3
0
above
[4]
above2
[4]
above2
[3, 2, 1]
above2
1
1
above
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-86-73e983c9ab93> in <module>()
----> 1 ga()
1 frames
<ipython-input-85-0ceb6003f3fa> in <listcomp>(.0)
17 print(i)
18 print("above")
---> 19 fitness = [value(population[j][i]) for j in range(len(population[i]))]
20 fitMax = -float('inf')
21
IndexError: string index out of range
我正在修改这段代码,现在我迷路了。我有什么要改变的?感谢你的帮助
解决方案
推荐阅读
- angular - 如何将 JSON 请求正文的值设置为数组而不是字符串
- wordpress - 使用过滤器更改默认页面标题 wordpress
- powershell - 是否可以使用 CmdLet 在 C# 中编写 PowerShell 提示函数?
- python - 如何在views.py中返回两个字典
- java - 如何使用 Java 代码用特定模式替换字符串中的未知子字符串?
- html - 为什么我的照片没有显示完整的自我?
- javascript - 如何将 signalR 聊天消息保存到数据库
- javascript - 剑道网格将最小值和最大值设置到另一列
- c# - 如何确定是否可以使用 CancellationTokenSource 取消某个异步任务?
- c - 创建一个长缓冲区然后将 strdup 放入一个新变量是保存来自 scanf 的任何输入的最佳方法吗?