Representing a Tree in Python

CTO debatem1 at gmail.com
Wed May 13 00:54:13 EDT 2009


On May 13, 12:10 am, godshorse <chinthak... at gmail.com> wrote:
> Hello,
>
> I want to find out the shortest path tree from a root to several nodes
> in a graph data structure. I found a Dijkstra code from internet that
> finds shortest path between only two nodes. How can i extend it to a
> tree?. And what is the best way to represent a tree in Python?.
>
> Thank you,

Well, I'm biased, but I like <URL: http://graphine.org>.
As an example, to build a five node tree:

>>> from graph.base import Graph
>>> g = Graph()
>>> for i in range(5):
...     g.add_node(i)
...
>>> g.add_edge(0, 1)
>>> g.add_edge(0, 2)
>>> g.add_edge(1, 3)
>>> g.add_edge(1, 4)

And to find the shortest path between, say, node 0 and node 4:

>>> start = g[0]
>>> end = g[4]
>>> distance, edges = g.get_shortest_paths(start)[end]
>>> distance
2
>>> edges
[Edge(name=(0,1)), Edge(name=(1,4))]

Let me know what you think if you decide to use it- I'm looking for
feedback.

Geremy Condra



More information about the Python-list mailing list