Skip to content

Instantly share code, notes, and snippets.

@atomictom
Created June 7, 2014 23:45
Show Gist options
  • Save atomictom/506e7e18a9eb98d25471 to your computer and use it in GitHub Desktop.
Save atomictom/506e7e18a9eb98d25471 to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# TODO: Construct a topological ordering for the pushes so they happen
# correctly regardless of their order in the relations.txt file
import re
import sys
import os.path
from exeption import ValueError
class Graph(object):
def __init__(self):
pass
def add_edge(self, pusher, receiver):
pass
def remove_edge(self, start, end):
pass
def has_edges(self):
pass
def get_edges(self, node):
pass
def get_source_nodes(self):
# set(graph) - set(node for node in graph[key] for key in graph)
pass
def parse_line(line, graph):
# Remove everything after the first '#'
first_comment = line.find("#")
line = line[:first_comment]
match = re.match(r'(.*) -> (.*)', line)
if match:
pusher = match.group(1)
receiver = match.group(2)
graph.add_node(pusher, receiver)
return graph
def topological_sort(graph):
sorted_list = []
source_nodes = graph.get_source_nodes()
while source_nodes:
node = source_nodes.pop()
sorted_list.append(node)
for end_node in graph.get_edges(node):
graph.remove_edge(node, end_node)
if graph.is_source(end_node):
source_nodes.add(end_node)
if graph.has_edges():
raise ValueError("Graph is not a DAG; it has cycles.")
return sorted_list
# try:
# with open(pusher) as f1, open(receiver) as f2:
# pusher_set = set(f1.readlines())
# pushed_set = set(f2.readlines())
# except IOError as e:
# print e
# print "Invalid relations.txt -- exiting"
# sys.exit(1)
#
# print match.group(0)
# print "-----------------------------------"
# with open(receiver, 'a') as out:
# print "".join(pusher_set - pushed_set)
# out.writelines(pusher_set - pushed_set)
# print
with open("/home/thomas/.cmus/relations.txt") as f:
lines = f.readlines()
for line in lines:
parse_line(line)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment