Last active
August 29, 2015 14:25
-
-
Save miku/cc492fab210b8fcd4004 to your computer and use it in GitHub Desktop.
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
#!/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