Guest User

Untitled

a guest
Jun 24th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. def topological_sort(graph):
  2.  
  3. is_visit = dict((node,False) for node in graph )
  4. order = []
  5. count = 0
  6.  
  7. def dfs(graph,start_node):
  8.  
  9. for end_node in graph[start_node]:
  10. if not is_visit[end_node]:
  11. is_visit[end_node] = True
  12. dfs(graph,end_node)
  13. order.append(start_node)
  14.  
  15. for start_node in graph:
  16. if not is_visit[start_node]:
  17. is_visit[start_node] = True
  18. dfs(graph,start_node)
  19. order.append(" ")
  20. return order
  21.  
  22. def read_file():
  23. list1 = []
  24. f = open("list.txt","r")
  25. line = f.readline()
  26. while line:
  27. line = line.split(',')
  28. for index,item in enumerate(line):
  29. line[index] = eval(item)
  30. list1.append(line)
  31. line = f.readline()
  32. f.close()
  33. dict1 ={}
  34. for k,v in enumerate(list1):
  35. dict1[k] =v
  36. return dict1
  37.  
  38. def main():
  39. graph = read_file()
  40. order_list = topological_sort(graph)
  41. f = open("dfs.txt","w")
  42. i = 0
  43. count = 0
  44. while i < len(order_list):
  45. if order_list[i] == " ":
  46. f.write("\n")
  47. count +=1
  48. else:
  49. f.write(str(i-count)+","+str(order_list[i]))
  50. f.write("\n")
  51. i+=1
  52. f.close()
  53.  
  54. main()
Add Comment
Please, Sign In to add comment