blob: 34bf6f50306a04a9bd5f092be8df68c379e87635 [file] [log] [blame]
Sapan Bhatia24836f12013-08-27 10:16:05 -04001#!/usr/bin/python
2
3import time
4import traceback
5import commands
6import threading
7import json
8
9from datetime import datetime
10from collections import defaultdict
11
12def toposort(g, steps):
13 reverse = {}
14
15 for k,v in g.items():
16 for rk in v:
17 try:
18 reverse[rk].append(k)
19 except:
20 reverse[rk]=k
21
22 sources = []
23 for k,v in g.items():
24 if not reverse.has_key(k):
25 sources.append(k)
26
27
28 for k,v in reverse.iteritems():
29 if (not v):
30 sources.append(k)
31
32 order = []
33 marked = []
34 while sources:
35 n = sources.pop()
36 try:
37 for m in g[n]:
38 if m not in marked:
39 sources.append(m)
40 marked.append(m)
41 except KeyError:
42 pass
43 if (n in steps):
44 order.append(n)
45
46 return order
47
48print toposort({'a':'b','b':'c','c':'d','d':'c'},['d','c','b','a'])