Skip to content

Commit

Permalink
ENH: updated cycle detection to pop sorted key
Browse files Browse the repository at this point in the history
`pop_key` will pop an item from the graph that has the fewest dependencies
In the case of a tie, the winners will be sorted alphabetically.

cc @mattpap @asmeurer
  • Loading branch information
srossross committed Nov 20, 2014
1 parent def6c01 commit 0be8171
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 6 deletions.
22 changes: 17 additions & 5 deletions conda/toposort.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,21 @@ def _toposort(data):
msg = 'Cyclic dependencies exist among these items: {}'
raise ValueError(msg.format(' -> '.join(repr(x) for x in data.keys())))

def pop_key(data):
'''
Pop an item from the graph that has the fewest dependencies in the case of a tie
The winners will be sorted alphabetically
'''
items = sorted(data.items(), key=lambda (k, v): (len(v), k))
key = items[0][0]

data.pop(key)

for dep in data.values():
dep.discard(key)

return key

def _safe_toposort(data):
"""Dependencies are expressed as a dictionary whose keys are items
and whose values are a set of dependent items. Output is a list of
Expand All @@ -64,14 +79,11 @@ def _safe_toposort(data):
yield value
except ValueError as err:
log.warn(err.args[0])

if not data:
return

key, _ = data.popitem()
yield key

for dep in data.values():
dep.discard(key)
yield pop_key(data)

t = _toposort(data)

Expand Down
12 changes: 11 additions & 1 deletion tests/test_toposort.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,18 @@
import unittest
from conda.toposort import toposort
from conda.toposort import toposort, pop_key

class TopoSortTests(unittest.TestCase):

def test_pop_key(self):
key = pop_key({'a':{'b', 'c'}, 'b':{'c'}})
self.assertEqual(key, 'b')

key = pop_key({'a':{'b'}, 'b':{'c', 'a'}})
self.assertEqual(key, 'a')

key = pop_key({'a':{'b'}, 'b':{'a'}})
self.assertEqual(key, 'a')

def test_simple(self):
data = {'a':'bc', 'b':'c'}
results = toposort(data, safe=True)
Expand Down

0 comments on commit 0be8171

Please sign in to comment.