我正在努力实现功能。它应该是这样工作的:
import random
def pm(indA, indB):
size = min(len(indA), len(indB))
c1, c2 = [0] * size, [0] * size
# Initialize the position of each indices in the individuals
for i in range(1,size):
c1[indA[i]] = i
c2[indB[i]] = i
crosspoint1 = random.randint(0, size)
crosspoint2 = random.randint(0, size - 1)
if crosspoint2 >= crosspoint1:
crosspoint2 += 1
else: # Swap the two cx points
crosspoint1, crosspointt2 = crosspoint2, crosspoint1
for i in range(crosspoint1, crosspoint2):
# Keep track of the selected values
temp1 = indA[i]
temp2 = indB[i]
# Swap the matched value
indA[i], indA[c1[temp2]] = temp2, temp1
indB[i], indB[c2[temp1]] = temp1, temp2
# Position bookkeeping
c1[temp1], c1[temp2] = c1[temp2], c1[temp1]
c2[temp1], c2[temp2] = c2[temp2], c2[temp1]
return indA, indB
a,b = pm([3, 4, 8, 2, 7, 1, 6, 5],[4, 2, 5, 1, 6, 8, 3, 7])
错误:
in pm
c1[indA[i]] = i
IndexError: list assignment index out of range
c1
超出范围,因为在第四个索引处的for
中,indA[4]的值是6。 c1指数的范围是0-5(长度是6)。你知道吗与
c1[indA[i]] = i
你试着做c1[6] = 4
不确定你的代码中是否有其他错误(我没有运行它),但下面是对此的解释。在Python中(与大多数其他语言一样),列出了(更精确地说是序列)索引是基于0的:
总结您的问题:
要解决问题,应该使用有效的索引值。或者:
在indA和indB中有适当的值(这是我选择的值):
减去1,当您遇到用作索引的indA或indB中的值时:
一般的建议是:每当你遇到错误时,在错误行之前加上print语句(打印其中的部分内容),这可能会给你一些线索,帮助你自己解决问题。你知道吗
@编辑0
过帐(稍加修改的版本)原始代码,并进行索引转换:
代码00.py:
输出(可能性之一(由于
random.randint
)):相关问题 更多 >
编程相关推荐