【问题标题】:find the shortest path between two points in a circular list in python在python的循环列表中找到两点之间的最短路径
【发布时间】:2016-07-31 07:41:18
【问题描述】:

我有一个如下列表: a =[1,2,3,4]

列表是一个循环列表。 列表中的值不代表节点,但列表的索引代表节点。 所以列表可能包含重复的元素。 例如,

if i take index (1,3)
(ie source is at index 1,and destination is at index 3) .
the shortest path is 1->4

if i take index (0,2) , i get two shortest paths
 1->2->3 and 
 1->4->3

我如何在 python 中进行此操作?

【问题讨论】:

  • 你已经尝试了什么?
  • 这里需要考虑一件事:在没有重复的列表中,循环列表中两点之间的最短路径等于 (a) 最短路径中的较小者不会“循环”,并且(b)最短路径。您应该能够扩展此逻辑以处理节点可以重复的情况。

标签: python algorithm


【解决方案1】:

看来这就是你想要的:

L = [1, 2, 3, 4, 5, 6]
a = L[1]
b = L[3]
cnt1 = []
cnt2 = []
for x in range(L.index(a), L.index(b) + 1):
    cnt1.append(L[x])
for x in range(L.index(a), L.index(b) -(len(L) + 1), -1):
    cnt2.append(L[x])

if len(cnt1) <= len(cnt2):
    print(cnt1)
else:
    print(cnt2)

【讨论】:

    猜你喜欢
    • 2018-02-10
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多