python简单有向无环图,带有cicle检测器和拓扑排序工具。
sdag2的Python项目详细描述
带有cicle检测器和拓扑排序工具的python简单有向图。
项目主页
此项目位于Github上。
脚本
tsort.py
标准输入源:
echo -e 'C A\nA B\nB D\nC D'| tsort.py
来自其他文件的源:
echo -e 'C A\nA B\nB D\nC D' > verticies.txt tsort.py verticies.txt
更多选项:
tsort.py --help Usage: tsort.py [options][FILE [OUT_FILE]] Options: -h, --help show this help message and exit -f FILE, --file=FILE With no FILE, or when FILE is -, read standard input. -o OUT_FILE, --out-file=OUT_FILE Write result to OUT_FILE, default is standard output. -s SEP, --separator=SEP Items separator, default is \s regex. -q QUIT_SEQ, --quit-sequence=QUIT_SEQ Stop read FILE where line equals QUIT_SEQ, default is :quit.
测试
importunittestfromsdag2importDAG,CycleDetectedExceptionclassDAGTest(unittest.TestCase):deftest_simple(self):''' Tests the verticles order in: C --> A --> B --> D '''dag=DAG()a=dag.add("A")b=dag.add("B")c=dag.add("C")d=dag.add("D")dag.add_edge(c,a)dag.add_edge(a,b)dag.add_edge(b,d)dag.add_edge(c,d)rs=dag.topologicaly()self.assertTrue(rs.index("C")<rs.index("A"))self.assertTrue(rs.index("A")<rs.index("B"))self.assertTrue(rs.index("B")<rs.index("D"))self.assertTrue(rs.index("C")<rs.index("D"))deftest_cicle_detect(self):''' Tests the verticles order in: C --> A --> B --> D -> C '''dag=DAG()a=dag.add("A")b=dag.add("B")c=dag.add("C")d=dag.add("D")dag.add_edge(c,a)dag.add_edge(a,b)dag.add_edge(b,d)dag.add_edge(c,d)try:# add cicle at A --> C --> Adag.add_edge(a,c)raiseException("Cycle not detected")exceptCycleDetectedException:passdefmain():unittest.main()if__name__=="__main__":main()