Skip to content

Instantly share code, notes, and snippets.

@gingerjoos
Last active December 13, 2018 12:00
Show Gist options
  • Save gingerjoos/e4b129e2ad436f0ec618ce3215370282 to your computer and use it in GitHub Desktop.
Save gingerjoos/e4b129e2ad436f0ec618ce3215370282 to your computer and use it in GitHub Desktop.
Test Networkx single_source_dijkstra_path with weighted edges
from pprint import pprint
import networkx as nx
g = nx.DiGraph()
"""
1-2-3-4-9
|_5_6_8
|_7
"""
data = [
(1, 2, 100),
(2, 3, 100),
(3, 4, 100),
(4, 9, 100),
(3, 5, 100),
(5, 6, 50),
(6, 8, 50),
(6, 7, 50),
]
print("WITH WEIGHTED EDGES")
print('#' * 100)
g.add_weighted_edges_from(data)
pprint(g.nodes)
pprint(g.edges.data())
print("Without cutoff")
pprint(nx.single_source_dijkstra_path(g, 1))
CUTOFF = 3
print("With cutoff of %d" % CUTOFF)
pprint(nx.single_source_dijkstra_path(g, 1, cutoff=CUTOFF))
print("WITHOUT WEIGHTED EDGES")
print('#' * 100)
g = nx.DiGraph()
g.add_edges_from([(x[0], x[1]) for x in data])
pprint(g.nodes)
pprint(g.edges.data())
print("Without cutoff")
pprint(nx.single_source_dijkstra_path(g, 1))
CUTOFF = 3
print("With cutoff of %d" % CUTOFF)
pprint(nx.single_source_dijkstra_path(g, 1, cutoff=CUTOFF))
"""
WITH WEIGHTED EDGES
####################################################################################################
NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9))
OutEdgeDataView([(1, 2, {'weight': 100}), (2, 3, {'weight': 100}), (3, 4, {'weight': 100}), (3, 5, {'weight': 100}), (4, 9, {'weight': 100}), (5, 6, {'weight': 50}), (6, 8, {'weight': 50}), (6, 7, {'weight': 50})])
Without cutoff
{1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 5],
6: [1, 2, 3, 5, 6],
7: [1, 2, 3, 5, 6, 7],
8: [1, 2, 3, 5, 6, 8],
9: [1, 2, 3, 4, 9]}
With cutoff of 3
{1: [1]}
WITHOUT WEIGHTED EDGES
####################################################################################################
NodeView((1, 2, 3, 4, 5, 6, 7, 8, 9))
OutEdgeDataView([(1, 2, {}), (2, 3, {}), (3, 4, {}), (3, 5, {}), (4, 9, {}), (5, 6, {}), (6, 8, {}), (6, 7, {})])
Without cutoff
{1: [1],
2: [1, 2],
3: [1, 2, 3],
4: [1, 2, 3, 4],
5: [1, 2, 3, 5],
6: [1, 2, 3, 5, 6],
7: [1, 2, 3, 5, 6, 7],
8: [1, 2, 3, 5, 6, 8],
9: [1, 2, 3, 4, 9]}
With cutoff of 3
{1: [1], 2: [1, 2], 3: [1, 2, 3], 4: [1, 2, 3, 4], 5: [1, 2, 3, 5]}
"""
# versions tried: networkx==2.2
# networkx==2.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment