使用 heapq 应用 Dijkstra:“生成器”对象不可下标

如何解决使用 heapq 应用 Dijkstra:“生成器”对象不可下标

正如标题所示,我正在尝试使用 Heapq 应用 dijkstra 算法(在 python 中的 dijksta 上关注 bogotobogo.com 并稍作修改 - 长链接;无法输入),并且我收到 TypeError: 'generator'对象不能通过 heapq.heappop 在堆化列表上的结果下标(在下面的代码中,我使用了 print('the question is in the line above ... ') 来定位错误),我试图避免生成器将首先生成的情况(如在列表理解中使用元组 - https://stackoverflow.com/a/56723524/7765766)但没有运气。 感谢您的帮助,因为这里的移动范围很窄。

import sys
import heapq
# making the vertices
class Vertex:
    """
    a class for making the vertex data structure that will be used to compose the graph and added to the shortest path.
    """
    def __init__(self,node_id):
        self.id = node_id
        self.distance = sys.maxsize
        self.visited = False
        # adding the adjacent
        self.neighbors = {}
        #empty object holding previous vertices
        self.previous = {} 
        
    def add_neighbors(self,neighbor,cost=0):
        # adding neighbors to the node when it is traversed
        self.neighbors[neighbor] = cost
    
    def get_neighbors(self):
        return self.neighbors
    
    def get_cost(self,neighbor):
        # get the weigh previously set on add_neighbors.
        return self.neighbors[neighbor]

    def set_visited(self):
        self.visited=True
    
    def set_distance(self,distance):
        self.distance = distance
    
    def get_distance(self):
        return self.distance

    def add_previous(self,previous):
        self.previous.append(previous)
    
    def get_previous(self):
        return self.previous

    def get_id(self):
        return self.id

    # def __getitem__(self,item):
    #     return self.neighbors[item]

    def __lt__(self,other_vertex):
        # this is used by python class for making comparsions -> required by the heapq
        return self.distance < other_vertex.distance

class Graph:
    def __init__(self):
        self.vertices_dict = {}
        self.num_vertices = 0

    def __iter__(self): # this will cause this class to be iterable
        return iter(self.vertices_dict.values())

    def get_dict_values(self):
        return self.vertices_dict.value()
    
    def add_vertex(self,node):
        new_vertex = Vertex(node)
        self.vertices_dict[node] = new_vertex
        self.num_vertices+=1
        return new_vertex
    
    def get_vertex(self,node):
        if node in self.vertices_dict:
            return self.vertices_dict[node]
        else:
            return None

        
    def construct_edge(self,From,to,cost=0):
        """
            take from and to (Vertices) to make the edge,check if these Vertices already exists on the vertices_dict 
            if not add them,and then call Vertex add_neighbors() method. 
        """
        if From not in self.vertices_dict:
            self.add_vertex(From)
        elif to not in self.vertices_dict:
            self.add_vertex(to)
        self.vertices_dict[From].add_neighbors(self.vertices_dict[to],cost)
        self.vertices_dict[to].add_neighbors(self.vertices_dict[From],cost)


    def construct_shortest_path(self,v,path):
        """
            recursively construct the shortest path from the vertex previous.
        """
        if v.previous:
            path.append(v.previous.get_id())
            # recursion
            construct_shortest_path(v.previous,path)
    

def dijkstra(graph,start,end):
    """
        1. adjust the distance of the start and add it to a list of unvisited_vertices "also known as openSet"
        2. get vertices and their indexes from the graph.
        3. loop until the len of unvisited_vertices equals 0.
        4. pop the first item of the unvisited_vertices and adjust it's visited value,name the item current.
        5. loop the neighbors of current,and check if it is already visited
             5.1 if not make a new distance equals to current vertex distance+ the cost from current ot next
             if this distance is less the distance of the neighbor,assign it to the neighbor instead and
             assign previous in the neighbors properties to current so you can keep track of previous vertices.
             if it is not less the distance of the nighbor don't do anything.
             
        6. the shortest path is stored in the previous of the nodes,another function has to handle extracting the 
            path (construct_shortest_path).
        note that the dijkstra function steps is slightly more complicated as heaps are used to organize data.  

    """
    start.set_distance(0)
    unvisited_nodes = [[vertex.get_distance(),vertex] for vertex in graph]
    #unvisited_nodes.append(start) # the start is assumed to be outer to the graph (not added to it already)
    # heapify the list so the the least distance is at the begining
    print('Before being heapified:',unvisited_nodes)
    heapq.heapify(unvisited_nodes)
    print(unvisited_nodes)
    while(len(unvisited_nodes)):
        heap_tuple = heapq.heappop(unvisited_nodes) # using heappop instead of pop.
        print("Heap tuple:",heap_tuple)
        print("Heap vertex:",heap_tuple[1])
        print("the problem is in the line above  ... ")
        current = heap_tuple[1]
        print('Current:',current)
        current.set_visited()
        if current==end:
            break
        for next in current.neighbors:
            if next.visited:
                continue
            tentative_distance = current.get_distance()+current.get_cost(next)
            if tentative_distance < next.get_distance():
                next.set_distance = tentative_distance
                next.previous = current
            else:
                continue
        
        # heap rebuild (i don't believe this is a good practice,there should be another way to refresh the heapq)
        # empty  the heap 
        while(len(unvisited_nodes)):
            heapq.heappop(unvisited_nodes)
        # again add vertices unvisited to it
        unvisited_nodes.append([v.get_distance(),v] for v in graph)
        heapq.heapify(unvisited_nodes)
        print('Reached the end')


if __name__ == '__main__':

    g = Graph()

    g.add_vertex('a')
    g.add_vertex('b')
    g.add_vertex('c')
    g.add_vertex('d')
    g.add_vertex('e')
    g.add_vertex('f')

    g.construct_edge('a','b',7)  
    g.construct_edge('a','c',9)
    g.construct_edge('a','f',14)
    g.construct_edge('b',10)
    g.construct_edge('b','d',15)
    g.construct_edge('c',11)
    g.construct_edge('c',2)
    g.construct_edge('d','e',6)
    g.construct_edge('e',9)

    print ('Graph data:',g)
    for v in g.vertices_dict.values():
        for w in v.get_neighbors():
            vid = v.get_id()
            wid = w.get_id()
            txt = '{},{},{}'.format(vid,wid,v.get_cost(w))
            print(txt)

    dijkstra(g,g.get_vertex('a'),g.get_vertex('e')) 

    target = g.get_vertex('e')
    path = [target.get_id()]
    shortest(target,path)
    tx = 'The shortest path:{}'.format(path[::-1])
    print(tx)

解决方法

在函数 dijkstra 的倒数第三行中,您仍在使用生成器。

unvisited_nodes.append((v.get_distance(),v) for v in graph)

将其转换为列表以通过订阅使用访问权限。

for v in graph:
    unvisited_nodes.append([v.get_distance(),v])
,

我正在添加另一个答案作为对您发布的关于无限循环的问题的回复。

我在这里查看了 3 个视频:

  1. https://www.coursera.org/learn/algorithms-graphs-data-structures/lecture/rxrPa/dijkstras-shortest-path-algorithm
  2. https://www.coursera.org/learn/algorithms-graphs-data-structures/lecture/Jfvmn/dijkstras-algorithm-examples
  3. https://www.coursera.org/learn/algorithms-graphs-data-structures/lecture/Pbpp9/dijkstras-algorithm-implementation-and-running-time

然后使用您的 Vertex 和 Graph 代码但修改了 djikstra 函数以执行以下操作:

  1. 创建起始邻居列表
  2. 选择最少的邻居节点
  3. 改变所选节点邻居的距离值
  4. 重复直到列表为空,因为所有其他都没有连接到启动所以我们不在乎

整个文件粘贴在下面

import sys
import heapq
# making the vertices


class Vertex:
    """
    a class for making the vertex data structure that will be used to compose the graph and added to the shortest path. # noqa:E501
    """
    def __init__(self,node_id):
        self.id = node_id
        self.distance = sys.maxsize
        self.visited = False
        # adding the adjacent
        self.neighbors = {}
        # empty object holding previous vertices
        self.previous = None

    def __str__(self):
        return f'Id={self.id},Dis={self.distance};'

    def __repr__(self):
        return f'Id={self.id},Dis={self.distance};'

    def add_neighbors(self,neighbor,cost=0):
        # adding neighbors to the node when it is traversed
        self.neighbors[neighbor] = cost

    def get_neighbors(self):
        return self.neighbors

    def get_cost(self,neighbor):
        # get the weigh previously set on add_neighbors.
        return self.neighbors[neighbor]

    def set_visited(self):
        self.visited = True

    def set_distance(self,distance):
        self.distance = distance

    def get_distance(self):
        return self.distance

    def add_previous(self,previous):
        self.previous.append(previous)

    def get_previous(self):
        return self.previous

    def get_id(self):
        return self.id

    # def __getitem__(self,item):
    #     return self.neighbors[item]

    def __lt__(self,other_vertex):
        # this is used by python class for making comparsions -> required by the heapq  # noqa:E501
        return self.distance < other_vertex.distance


class Graph:
    def __init__(self):
        self.vertices_dict = {}
        self.num_vertices = 0

    def __iter__(self):  # this will cause this class to be iterable
        return iter(self.vertices_dict.values())

    def get_dict_values(self):
        return self.vertices_dict.value()

    def add_vertex(self,node):
        new_vertex = Vertex(node)
        self.vertices_dict[node] = new_vertex
        self.num_vertices += 1
        return new_vertex

    def get_vertex(self,node):
        if node in self.vertices_dict:
            return self.vertices_dict[node]
        else:
            return None

    def construct_edge(self,From,to,cost=0):
        """
            take from and to (Vertices) to make the edge,check if these Vertices already exists on the vertices_dict # noqa:E501
            if not add them,and then call Vertex add_neighbors() method.
        """
        if From not in self.vertices_dict:
            self.add_vertex(From)
        if to not in self.vertices_dict:
            self.add_vertex(to)
        self.vertices_dict[From].add_neighbors(self.vertices_dict[to],cost)
        self.vertices_dict[to].add_neighbors(self.vertices_dict[From],cost)

    def construct_shortest_path(self,v,path):
        for k,vvv in self.vertices_dict.items():
            print(vvv)
        """
            recursively construct the shortest path from the vertex previous.
        """
        if v.previous:
            path.append(v.previous.get_id())
            # recursion
            self.construct_shortest_path(v.previous,path)


def dijkstra(graph,start,end):
    """
        1. adjust the distance of the start and add it to a list of unvisited_vertices "also known as openSet" # noqa:E501
        2. get vertices and their indexes from the graph.
        3. loop until the len of unvisited_vertices equals 0.
        4. pop the first item of the unvisited_vertices and adjust it's visited value,name the item current.
        5. loop the neighbors of current,and check if it is already visited
             5.1 if not make a new distance equals to current vertex distance+ the cost from current ot next
             if this distance is less the distance of the neighbor,assign it to the neighbor instead and
             assign previous +current.get_costhortest_path).
        note that the dijkstra function steps is slightly more complicated as heaps are used to organize data.

    """
    start.set_distance(0)
    # 1. create list of start neighbors
    # 2. pick least neighbor node
    # 3. change distance values of picked node's neighbours
    # 4. repeat until list is empty because all else are not connected to start so we dont care # noqa:E501
    unvisited_nodes = [vertex for vertex in start.get_neighbors()]  # 1 # noqa:E501
    # unvisited_nodes.append(start) # the start is assumed to be outer to the graph (not added to it already) # noqa:E501
    # heapify the list so the the least distance is at the begining
    # print('Before being heapified:',unvisited_nodes)
    start.set_visited()
    for vertics in unvisited_nodes:
        vertics.previous = start
        vertics.distance = start.get_cost(vertics)
    heapq.heapify(unvisited_nodes)
    print(unvisited_nodes)
    # import pdb
    # pdb.set_trace()
    while(len(unvisited_nodes)):
        vertics_from_heap = heapq.heappop(unvisited_nodes)  # 2 # using heappop instead of pop. # noqa:E501
        # print("Heap tuple:",heap_tuple)
        # print("Heap vertex:",heap_tuple[1])
        # print("the problem is in the line above  ... ")
        current = vertics_from_heap
        print('Current:',current)
        current.set_visited()
        if current == end:
            # current.previous = start
            break
        for next in current.neighbors:
            if next.visited:
                continue
            tentative_distance = current.get_distance()+current.get_cost(next)
            if next not in unvisited_nodes:
                heapq.heappush(unvisited_nodes,next)
            if tentative_distance < next.get_distance():
                next.set_distance = tentative_distance
                next.previous = current
        # heap rebuild (i don't believe this is a good practice,there should be another way to refresh the heapq) # noqa:E501
        # empty  the heap
        # while(len(unvisited_nodes)):
        #    heapq.heappop(unvisited_nodes)
        # again add vertices unvisited to it
        # for v in graph:
        #    unvisited_nodes.append([v.get_distance(),v])
        # heapq.heapify(unvisited_nodes)
        # print('Reached the end')


if __name__ == '__main__':

    g = Graph()

    g.add_vertex('a')
    g.add_vertex('b')
    g.add_vertex('c')
    g.add_vertex('d')
    g.add_vertex('e')
    g.add_vertex('f')

    g.construct_edge('a','b',7)
    g.construct_edge('a','c',9)
    g.construct_edge('a','f',14)
    g.construct_edge('b',10)
    g.construct_edge('b','d',15)
    g.construct_edge('c',11)
    g.construct_edge('c',2)
    g.construct_edge('d','e',6)
    g.construct_edge('e',9)

    print('Graph data:',g)
    for v in g.vertices_dict.values():
        for w in v.get_neighbors():
            vid = v.get_id()
            wid = w.get_id()
            txt = '{},{},{}'.format(vid,wid,v.get_cost(w))
            print(txt)

    dijkstra(g,g.get_vertex('a'),g.get_vertex('e'))

    target = g.get_vertex('e')
    path = [target.get_id()]
    g.construct_shortest_path(target,path)
    tx = 'The shortest path:{}'.format(path[::-1])
    print(tx)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-