Python中的基本贪婪搜索

时间:2017-01-19 18:36:21

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

def basic_greedy():

    start = 1
    mindist = d_dict[(1,2)]
    m = 0

    while len(tour)!=size:
        tour.append(start)
        for k in range(len(cities)):
            if cities[k] not in tour:
                if d_dict[(start,cities[k])]<mindist:
                    mindist = d_dict[(start,cities[k])]
                    m = k
        start = cities[m]

    return tour

这是我在Python中进行基本贪婪搜索的代码。 开始是开始城市,游览是一个列表,其中包含城市以便访问它们,城市是包含所有城市的列表1到大小(1,2,3,4 ..... 12..size),其中size是城市数量。 d_dict 是一个包含每对可能城市之间距离的字典。 mindist m 只是跟踪最近邻居等的临时变量。

我希望代码从城市1开始,移动到最近的邻居,然后到最近,直到每个城市都被覆盖一次。我希望这个代码的输出与城市1到8的 [1,5,3,8,4,6,2,7] 一致(访问所有的一些组合城市恰好一次)但我得到 [1,7,7,7,7,7,7,7] 。怎么了?

2 个答案:

答案 0 :(得分:1)

问题: 一般来说,问题是不明确的。代码是完整的。但是,让我提供一些基本的指示。希望能帮助到你。这就是......

  1. 一旦找到并添加了一个城市,你就需要摆脱for循环(看起来像这样,检查,仔细检查)。
  2. 代码不完整。例如:(a)您如何访问列表导览? (b)未定义的大小
  3. 确保您不会重新考虑或添加已在旅游列表中访问过的城市(看起来像是这样,请仔细检查,重新检查)。
  4. 建议使用图形/节点技术来实现这种贪婪搜索。

答案 1 :(得分:0)

def basic_greedy():
    # greedy search algorithm
    d_dict = {1: [(1, 2), (2, 15), (3, 30)], 2: [(1, 30), (7, 10)]}  # dict of lists of tuples such that nodei : [ (neighbourj, distancej), .... ]
    currentCity = 1
    tour = []   # list of covered nodes
    tour.append(currentCity)
    distanceTravelled = 0   # distance travelled in tour
    while len(set([neighbourCity for (neighbourCity, distance) in d_dict.get(currentCity, [])]).difference(set(tour))) > 0:  # set(currentCityNeighbours) - set(visitedNodes)
        # way 1 starts
        minDistanceNeighbour = None
        minDistance = None
        for eachNeighbour, eachNeighbourdDistance in d_dict[currentCity]:
            if eachNeighbour != currentCity and eachNeighbour not in tour:
                if minDistance is not None:
                    if minDistance > eachNeighbourdDistance:
                        minDistance = eachNeighbourdDistance
                        minDistanceNeighbour = eachNeighbour
                else:
                    minDistance = eachNeighbourdDistance
                    minDistanceNeighbour = eachNeighbour
        nearestNeigbhourCity = (minDistanceNeighbour, minDistance)
        # way 1 ends
        # way 2 starts
        # nearestNeigbhourCity = min(d_dict[currentCity], key=lambda someList: someList[1] if someList[0] not in tour else 1000000000)  # else part returns some very large number
        # way 2 ends
        tour.append(nearestNeigbhourCity[0])
        currentCity = nearestNeigbhourCity[0]
        distanceTravelled += nearestNeigbhourCity[1]
    print(tour)
    print(distanceTravelled)

这是你要求的吗?我可能已经改变了距离字典的结构和其他一些变量,但这并没有影响贪婪的方法逻辑,希望这对你有用...... 编辑了我的答案,就像我第一次在nearestNeighbourCity的所有邻居中找到currentCity,但现在我在当前城市的所有未访问的邻居中找到nearestNeighbourCity,并且我已经完成了使用两种方式way 1way 2