用Python加2opt算法求解旅行商问题

2024-04-24 23:57:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python中找不到任何完整的2-opt算法实现,所以我试图在这个项目.中添加缺少的部分解决方案。但是在这个项目中给出了最终的路线与交叉路径。为了解决这个问题,我在代码中实现了两个opt算法。但毕竟,最后的路线又是交叉。它是我添加到这个source的双opt算法

我从这里得到这个函数:two-opt

def two_optt(self, route):
    best = route
    improved = True
    while improved:
        improved = False
        for i in range(1, len(route.route) - 2):
            for j in range(i + 1, len(route.route)):
                if j - i == 1: continue
                new_route=Route()
                new_route.route = route.route[:]
                new_route.recalc_rt_len()

                new_route.route[i:j] = route.route[j-1:i - 1:-1]  # this is the 2woptSwap
                new_route.recalc_rt_len()
                if new_route.length < best.length:
                    best = new_route

                    improved = True
            route=best

    best.recalc_rt_len()
    return best

我把这个函数添加到了GA类中,我在变异调用之后调用了这个函数

    for route in descendant_pop.rt_pop:
        if random.random() < 0.3:
            self.mutate(route)
        self.two_optt(route) `

我又得到了一个交叉路径的解。我该怎么办?是我加了两个opt函数错了,还是我调用错了?你知道吗


Tags: 函数inself算法newforlenif