在Python中寻找欧洲之旅

时间:2016-07-20 01:03:37

标签: python algorithm

通过关于算法的Udacity课程并创建以下函数来确定给定图形的欧拉路径。虽然我通过了样本测试,但答案是不被接受的。有人知道为什么吗?感谢您的任何指示!

# Find Eulerian Tour
#
# Write a function that takes in a graph
# represented as a list of tuples
# and return a list of nodes that
# you would follow on an Eulerian Tour
#
# For example, if the input graph was
# [(1, 2), (2, 3), (3, 1)]
# A possible Eulerian tour would be [1, 2, 3, 1]

def get_degree(tour):
    degree = {}
    for x, y in tour:
        degree[x] = degree.get(x, 0) + 1
        degree[y] = degree.get(y, 0) + 1
    return degree


def find_eulerian_tour(graph):
    tour = []
    deg = get_degree(graph)
    for node in deg:
        if deg.get(node)%2==1:
            first = node
        else:
            first = list(deg.keys())[0]

    node = first
    tour.append(node)
    checkpoint=[]
    while graph:
        edges = [t for t in graph if t[0] == node or t[1] == node]

        if not edges:
            tour = checkpoint[-1][0]
            graph = checkpoint[-1][1]
            node = checkpoint[-1][2]
            edges = [t for t in graph if (t[0] == node or t[1] == node) and t != checkpoint[-1][3]]
            checkpoint.remove(checkpoint[-1])

        path = edges[0]
        if len(edges) > 1:
            checkpoint.append([list(tour), list(graph), int(node), tuple(path)])

        if path[0] == node:
            node = path[1]
        else:
            node = path[0]

        tour.append(node)
        graph.remove(path)

    return tour

def test():
    tour = [(1, 2), (2, 3), (3, 1)]
    tour2 = [(1, 2), (2, 3), (3,4), (4,1), (2,4)]
    tour3 = [(1,2),(2,3),(1,3),(2,4),(2,5),(4,5)]
    print(find_eulerian_tour(tour))
    print(find_eulerian_tour(tour2))
    print(find_eulerian_tour(tour3))


test()

1 个答案:

答案 0 :(得分:0)

我在Udacity上经历了同样的课程。我找到了解决方案。检查解决方案here