Мы хотим решить следующую проблему на Python:
Есть маршрут с дугами / кортежами [i,j]. Например: [(0,10),(11,0),(10,11)].
[0,10,11,0].Кто-нибудь знает, как это решить?
@Jayjayyy Да, мы всегда начинаем и заканчиваем на 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]
Без вопросов, это было очень полезно. Большое спасибо!
Используйте словарь и удаляйте узлы по мере их поиска:
nodes = [(0, 10), (11, 0), (10, 11)]
d = dict(nodes)
chain = [0]
while d:
chain.append(d.pop(chain[-1]))
я не понял вопроса