TSP基本贪婪算法的无限循环

时间:2017-01-11 15:25:57

标签: python algorithm infinite-loop greedy traveling-salesman

我正在尝试在Python 2.7中实现旅行商问题的基本贪婪算法。

我有一个名为 d_dict = {(city1,city2):distance} 的词典,用于存储城市之间的距离。在这里,所有城市都相互连接。我只需要到最近的邻居,直到所有城市都被覆盖,然后返回起始城市。这里,为方便起见,起始城市为1,即 st = 1 。有两个列表 rem ,用于存储未覆盖的城市和 cov ,它们按照覆盖的顺序存储城市。

我已经定义了一个名为 basic_greedy(x)的函数,它将城市x作为起始城市,计算它与所有未覆盖城市的距离(因为在这种情况下,每个城市都连接到每个城市) rem,然后最近的邻居从rem中移除,附加到cov并成为下一个开始城市。迭代地调用该函数直到rem变为空列表(即所有城市都被覆盖)。起始城市(或 root )最后只是附加到cov。这是我的代码:

#create two lists - 'covered' or 'cov': to store cities as they are covered in order.
#'remaining' or 'rem': list of uncovered cities.

cov = []
rem = [ x for x in range(1,size+1)]

global st
st = 1 #start city, initialized as 1
root =  st     #root of the graph - start of the tour


#######################################
#basic greedy search

#function definition - basic greedy search algorithm for the travelling salesman problem

def basic_greedy(x):

    #rem.remove(x)

    try:
        r = rem.index(x)
        del rem[r]
    except:
        pass

    cov.append(x)
    print (cov,rem)

    m=1
    chg = 0  #a temporary variable, counts number of changes in value of st
    if x < size:
        m = d_dict[(x,x+1)] #variable m shall keep track of the smallest distance
    elif x == size:
        m = d_dict[(x,x-1)]

    for k in rem:
        if d_dict[(x,k)] < m:
            m = d_dict[(x,k)]
            st = k


########################################

while len(rem)!= 0:
    basic_greedy(st)

cov.append(root)
print "Basic Greedy Search Tour: ",cov  #THE FINAL SEQUENCE

然而,当我运行它时,我得到一个无限循环,这只是无限附加的1。代码中的错误是什么?

(P.S。我尝试了多种方法,但几天都无法发现错误)

编辑:以下是12个城市的字典:

(1, 1) : 0 ,
(1, 2) : 32 ,
(1, 3) : 7 ,
(1, 4) : 13 ,
(1, 5) : 15 ,
(1, 6) : 21 ,
(1, 7) : 5 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 25 ,
(8, 3) : 20 ,
(8, 4) : 6 ,
(8, 5) : 10 ,
(8, 6) : 7 ,
(8, 7) : 50 ,
(8, 8) : 0 ,
(8, 9) : 20 ,
(8, 10) : 40 ,
(8, 11) : 32 ,
(8, 12) : 34 ,
(9, 1) : 40 ,
(9, 2) : 3 ,
(9, 3) : 30 ,
(9, 4) : 29 ,
(9, 5) : 6 ,
(9, 6) : 8 ,
(9, 7) : 53 ,
(9, 8) : 20 ,
(9, 9) : 0 ,
(9, 10) : 2 ,
(9, 11) : 15 ,
(9, 12) : 7 ,
(10, 1) : 31 ,
(10, 2) : 5 ,
(10, 3) : 50 ,
(10, 4) : 27 ,
(10, 5) : 8 ,
(10, 6) : 17 ,
(10, 7) : 30 ,
(10, 8) : 40 ,
(10, 9) : 2 ,
(10, 10) : 0 ,
(10, 11) : 15 ,
(10, 12) : 4 ,
(11, 1) : 9 ,
(11, 2) : 16 ,
(11, 3) : 21 ,
(11, 4) : 25 ,
(11, 5) : 15 ,
(11, 6) : 14 ,
(11, 7) : 6 ,
(11, 8) : 32 ,
(11, 9) : 15 ,
(11, 10) : 15 ,
(11, 11) : 0 ,
(11, 12) : 4 ,

0 个答案:

没有答案