Skip to content

Instantly share code, notes, and snippets.

@miku
Last active August 29, 2015 14:25
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 miku/cc492fab210b8fcd4004 to your computer and use it in GitHub Desktop.
Save miku/cc492fab210b8fcd4004 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python2
# coding: utf-8
def read(filename):
"""
Read a graph from a file. Returns a dictionary.
The file must be in the format:
SRC DST DST ...
SRC DST
...
where SRC and DST are names of nodes.
Node names must not contain whitespace.
"""
g = {}
with open(filename) as handle:
for line in handle:
line = line.strip()
if line == "":
continue
parts = line.split()
src = parts[0]
targets = parts[1:]
if src not in g:
g[src] = set()
for target in targets:
g[src].add(target)
return g
def write(filename, g):
""" Write dictionary `g` to file. """
with open(filename, "w") as handle:
for src, targets in g.iteritems():
handle.write("%s %s\n" % (src, " ".join(targets)))
if __name__ == '__main__':
g = {
"A": ["B", "C"],
"B": ["D"],
"C": ["B"],
}
write("test.g", g)
g = read("test.g")
print(g)
# {'A': set(['C', 'B']), 'C': set(['B']), 'B': set(['D'])}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment