尝试跨越两个孩子时列表索引超出范围

时间:2019-05-12 11:43:57

标签: python list genetic-algorithm

嗨,我正在尝试应用NSGA-II,我的逻辑很简单,我在范围内随机选择两个数字并应用交叉,但是代码给出了超出范围错误的索引

这是我的代码:

if($bul == "true"){
            while ($ai < count($sentencearr)){
                for($i = 0; $i<count($alpha); $i++){
                    if($sentencearr[$ai] == $alpha[$i]){
                        $answer[$ai] = $choicearray[$i];
                        $ia = count($alpha) + 1;
                    }else if($sentencearr[$ai] == $alphaup[$i]){
                        $answer[$ai] = $choicearrayup[$i];
                        $ia = count($alpha)+1;
                    }
                }
                $insert_arry = join($answer[$ai]);
                $sql = "insert into message(msg, name) values ('$insert_arry[$ai]', '$name')";
                $result=$conn->query($sql);
                header("Location:home.php");
                $ai++;
            }

我个人认为问题出在这部分

def make_child_pop(parent_set, child_set):
    for i in range(popul):
        r1 = random.randint(0, req-1)
        r2 = random.randint(0, req-2)
        c1=[]
        c2=[]
        if r2 >= r1:
            r2 += 1
        # r1, r2 crossover
        r3 = random.randint(0, req-1)
    try:
        c1 = parent_set[r1][:r3] + parent_set[r2][r3:]
        c2 = parent_set[r2][:r3] + parent_set[r1][r3:]
        except IndexError:
            print(parent_set, r3, r1, r2)

        # r4 : mutation
        r4 = random.randint(0, 99)
        r5 = random.randint(0, 99)
        if r4 < 100 * mutation_rate:
            r6 = random.randint(0, req-1)
            c1[r6] = not c1[r6]
        if r5 < 100 * mutation_rate:
            r6 = random.randint(0,req-1)
            c2[r6] = not c2[r6]
        child_set.append(c1)
        child_set.append(c2)
    child_set = child_set + copy.copy(parent_set)

任何帮助将不胜感激。

0 个答案:

没有答案