I think there is http://py-algorithm.blogspot.com/2011/09/blog-post.html enough information about topological sorting.
For example for matrix sorting there is such realization:
class Graph:
def __init__(self):
self.nodes=[[0,0,0,0,0,0],
[1,0,0,1,0,0],
[0,1,0,1,0,0],
[0,0,0,0,0,0],
[0,0,0,1,0,0]
];
self.count=range(len(self.nodes))
def GetInputNodesArray(self):
array = []
for i in self.count:
step=0
for j in self.count:
if self.nodes[i][j]==1:step+=1
array.insert(i,step)
return array;
def TopologicSort(self):
levels =[];
workArray = self.GetInputNodesArray();
completedCounter = 0;
currentLevel = 0;
while (completedCounter != len(self.nodes)):
for i in self.count:
if (workArray[i] == 0):
ind=0
#добавляем обработанную вершину
levels.insert(completedCounter,i);
for node in self.nodes:
if node[i]==1:
workArray[ind]-=1
ind+=1
workArray[i] = -1; # Помечаем вершину как обработанную
completedCounter+=1;
currentLevel+=1;
levels.reverse()
return levels#осталось выбрать в обратном порядке
It is on russian, so your can tranlate it, but I think algorithms should be clear enough.