我们想用Python解决以下问题:
有一条带有弧/元组[i,j]
的路线。例如:[(0,10),(11,0),(10,11)]
。
[0,10,11,0]
。有人知道如何解决这个问题吗?
答案 0 :(得分:0)
我想这只是学习如何使用Python进行某些操作的示例?看看下面的代码,这是一个非常基本的方法。不过,它不是经过优化的代码。
# Define a route by the steps you have to take from one origin to the
# new destination. These steps are provided as a list of tuples where
# the first element is the origin and the second element is the destination.
steps = [(0,10), (11,0), (10,11)]
# Start with origin 0
route = [0]
# Repeat until no steps left to take
while len(steps) > 0:
# The former destination is the last element of the current route
former_destination = route[-1]
# Browse through all remaining steps
for i, (origin, destination) in enumerate(steps):
# Skip this step if its origin and the former destination don't match
if origin != former_destination:
continue
# Remove the current step
steps.pop(i)
# Add new destination
route.append(destination)
break
print(route)
将打印哪个
[0, 10, 11, 0]
答案 1 :(得分:0)
使用字典和删除节点,你看看他们:
nodes = [(0, 10), (11, 0), (10, 11)]
d = dict(nodes)
chain = [0]
while d:
chain.append(d.pop(chain[-1]))