Skip to content

Instantly share code, notes, and snippets.

@st0le
Last active December 16, 2015 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save st0le/5455813 to your computer and use it in GitHub Desktop.
Save st0le/5455813 to your computer and use it in GitHub Desktop.
Representing Graphs in Python
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