Last active
December 16, 2015 15:28
-
-
Save st0le/5455813 to your computer and use it in GitHub Desktop.
Representing Graphs in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fileinput | |
# add_edge (u -> v) with weight w to graph g | |
def add_edge(graph,u,v,w): | |
if u in graph: #vertex u already in graph? | |
l = graph[u] #get list of neighbours | |
else: | |
graph[u] = l = list() #insert u into graph and assign an empty list of neighbours | |
l.append((v,w)) #append tuple (v,w) into the neighbour list | |
g = dict() #initialize graph | |
for line in fileinput.input(): | |
u,v,w = map(int,line.split()) | |
add_edge(g,u,v,w) | |
add_edge(g,v,u,w) #undirected graph, edges go both ways | |
print g |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment