Some questions regarding implementing Disjoint Set data structure in python

218 views Asked by At

So I just used the code available here: http://www.ics.uci.edu/~eppstein/PADS/UnionFind.py, but I have come across some problems about the code:

First of all, what does the method iter mean or do?

Second, suppose I originally have the following code:

set R=set(['A','B','C','D','E','F','G'])
R=UnionFind()

Then, how can I execute the usual operation for a set like print, add, etc? If I write print R, it only gives <main.UnionFind instance at 0x000000000A31F048>, which is obviously not what I want. If I write R.add('K') (add the new element 'K' to the set R), I get 'AttributeError: UnionFind instance has no attribute 'add''. Does it mean that I need to define an attribute for 'add'? How to do this?

If after a few union operations I have grouped 'A','B','C' to the same set, then if I want to know all the elements inside the set that 'A' is in (which is 'A','B','C'), what should I do?

thanks

1

There are 1 answers

0
Wolph On
  1. The iter function returns an iterator of the given object. In this case and iterator of self.parents which is a dict so the result will be an iterator over the keys of the dictionary.

  2. Given that code, the only response I can think of is SyntaxError.

Here's how you could use the UnionFind() class:

union_find = UnionFind()
a = 123
b = 456
c = 123
union_find.union(a, b, c)

print list(union_find)

The result will be: [456, 123]