{ "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": true }, "outputs": [], "source": [ "from collections import deque\n", "def topologicalOrdering(g):\n", " \n", " # find indegrees of each node\n", " out = reduce(lambda a,b: a+b, g.values())\n", " indegrees = {}\n", " for node in set(out + g.keys()):\n", " if node not in out:\n", " indegrees[node] = 0\n", " else:\n", " indegrees[node] = out.count(node)\n", "\n", " # collect set of all nodes in graph with zero indegrees\n", " candidates = deque()\n", " for node in indegrees:\n", " if indegrees[node] == 0:\n", " candidates.appendleft(node)\n", "\n", " L = [] # list for order of nodes\n", " \n", " # choose zero indegree node and remove it from graph\n", " while candidates:\n", " a = candidates.pop()\n", " L.append(a)\n", " if a in g:\n", " for b in g[a]:\n", " indegrees[b] -= 1\n", " if indegrees[b] == 0:\n", " candidates.appendleft(b) \n", " \n", " #if graph has edges that have not been removed/if there is a cycle\n", " for node in indegrees:\n", " if indegrees[node] != 0:\n", " return \"the input graph is not a DAG\"\n", " else:\n", " return L" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[1, 4, 5, 2, 3]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "graph = {1:[2], 2:[3], 4:[2], 5:[3]}\n", "topologicalOrdering(graph)" ] }, { "cell_type": "code", "execution_count": 70, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 2, 3, 4, 5, 6, 7, 10, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n" ] } ], "source": [ "g = dict()\n", "f = open('input/rosalind_ba5n.txt', 'r')\n", "for line in f:\n", " line = line.strip().split('->')\n", " g[int(line[0])] = map(int,line[1].split(','))\n", "print topologicalOrdering(g)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'e', 'c', 'f', 'd']" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "g = {'a': ['b', 'c', 'd', 'e', 'f'],\n", " 'b': ['c', 'f'],\n", " 'c': ['d'],\n", " 'd': [], \n", " 'e': ['d', 'f'],\n", " 'f': []}\n", "topologicalOrdering(g)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 2", "language": "python", "name": "python2" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 2 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython2", "version": "2.7.5" } }, "nbformat": 4, "nbformat_minor": 0 }