繁体   English   中英

Python-Dijkstra的算法

[英]Python - Dijkstra's Algorithm

我需要在Python中实现Dijkstra的算法。 但是,我必须使用2D数组来保存三段信息-前身,长度和未访问/访问的信息。 我知道在C中可以使用Struct,尽管我一直坚持如何在Python中做类似的事情,但我被告知有可能,但是我不知道如何诚实

为此创建一个类。

class XXX(object):
    def __init__(self, predecessor, length, visited):
        self.predecessor = predecessor
        self.length = length
        self.visited = visited

或使用collections.namedtuple,这对于保存没有自己的行为但具有命名成员的类似结构的复合类型特别酷: XXX = collections.namedtuple('XXX', 'predecessor length visited')

XXX(predecessor, length, visited)创建一个。

将该信息封装在Python对象中,就可以了。

或者,您可以在2d数组中简单地使用元组或字典:

width=10
height=10

my2darray = []
for x in range(width):
   my2darray[x]=[]

for x in range(width):
   for y in range(height):
      #here you set the tuple
      my2darray[x][y] = (n,l,v) 
      #or you can use a dict..
      my2darray[x][y] = dict(node=foo,length=12,visited=False)

如上所述,您可以使用对象的实例。

作者在python中有一个非常令人信服的Dijkstras python实现。

#
# This file contains the Python code from Program 16.16 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng.  All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_16.txt
#
class Algorithms(object):

    def DijkstrasAlgorithm(g, s):
        n = g.numberOfVertices
        table = Array(n)
        for v in xrange(n):
            table[v] = Algorithms.Entry()
        table[s].distance = 0
        queue = BinaryHeap(g.numberOfEdges)
        queue.enqueue(Association(0, g[s]))
        while not queue.isEmpty:
            assoc = queue.dequeueMin()
            v0 = assoc.value
            if not table[v0.number].known:
                table[v0.number].known = True
                for e in v0.emanatingEdges:
                    v1 = e.mateOf(v0)
                    d = table[v0.number].distance + e.weight
                    if table[v1.number].distance > d:

                        table[v1.number].distance = d
                        table[v1.number].predecessor = v0.number
                        queue.enqueue(Association(d, v1))
        result = DigraphAsLists(n)
        for v in xrange(n):
            result.addVertex(v, table[v].distance)
        for v in xrange(n):
            if v != s:
                result.addEdge(v, table[v].predecessor)
        return result
    DijkstrasAlgorithm = staticmethod(DijkstrasAlgorithm)

注意,通过调用Algorithms.Entry(),这些信息被“保留”在他正在构造的对象中。 Entry是一个类,其定义如下:

class Entry(object):
    """
    Data structure used in Dijkstra's and Prim's algorithms.
    """

    def __init__(self):
        """
        (Algorithms.Entry) -> None
        Constructor.
        """
        self.known = False
        self.distance = sys.maxint
        self.predecessor = sys.maxint

自我,自我,距离...就是这些信息。 他没有在构造函数( init )中显式设置它们,而是稍后进行设置。 在Python中,您可以使用点表示法访问属性。 例如:myObject = Entry()。 myObject.known,myObject.distance ...它们都是公共的。

Python是面向对象的语言。 因此,将其想象为从C中的结构迁移到C ++类。 您也可以在Python中使用相同的类结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM