一跳飞行挑战

时间:2017-08-22 15:53:09

标签: algorithm python-3.x data-structures

我有从源到目的地的航班元组列表。例如:[(2,3),(1,2),(3,1),(1,3),(3,2),(2,4),(4,1)]

我想返回所有航班的元组列表,这些元组之间有一个连接航班。例如,上面列表的答案是[(1,2),(1,3),(1,4),(2,1),(3,2),(3,4),(4) ,2),(4,3)]

我是python的初学者,并且已经尝试解决它已经有一段时间了,并提出了以下代码。 我的逻辑错了吗?我觉得我可以使用列表推导或其他方式更短的方式,但我不太确定。请给我关于如何解决这个问题的建议。

def one_hop(l):
    source = [i[0] for i in l]
    dest = [j[1] for j in l]
    (i, j, one) = (0, 0, [])
    for i in source:
        for j in dest:
            if source.index(i) != dest.index(j) and j in dest and i != j:
                index1 = dest.index(j)
                if source[index1] in dest and source[index1] != j and dest.index(source[index1]) != source.index(i) and i == source[dest.index(source[index1])]:
                    one.append((i,j))
    return one

1 个答案:

答案 0 :(得分:1)

当你要求理解时(虽然效率很低):

sorted(set((u[0],v[1]) for u in l for v in l if u[1]==v[0] and u[0]!=v[1]))