Skip to content

Commit

Permalink
Fixed a bug in unionfind.sets() where the set trees were incorrectly …
Browse files Browse the repository at this point in the history
…assumed to be flat.
  • Loading branch information
cjauvin committed Jan 15, 2014
1 parent 3c3f985 commit 1fd5d44
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions unionfind.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
with significant additional changes by D. Eppstein.
"""

from collections import defaultdict

class UnionFind:
"""Union-find data structure.
Expand Down Expand Up @@ -49,7 +51,7 @@ def __getitem__(self, object):
for ancestor in path:
self.parents[ancestor] = root
return root

def __iter__(self):
"""Iterate through all items ever found or unioned by this structure."""
return iter(self.parents)
Expand All @@ -65,8 +67,17 @@ def union(self, *objects):

def sets(self):
"""Return a list of each disjoint set"""
ret = {}
for k, v in self.parents.iteritems():
ret.setdefault(v, []).append(k)
ret = defaultdict(list)
for k, _ in self.parents.iteritems():
ret[self[k]].append(k)
return ret.values()


if __name__ == '__main__':

# test
uf = UnionFind()
uf.union(0, 1)
uf.union(2, 3)
uf.union(3, 0)
assert uf.sets() == [[0, 1, 2, 3]]

0 comments on commit 1fd5d44

Please sign in to comment.