Firstly, I've mostly done very trivial things with python, so I am not very comfortable with pythonic syntax. I am learning about disjoint sets, and have a basic understanding of the implementation.
I came across a python forest-implementation (not mine!) , and am having a lot of difficulty understanding how the dictionary in __init__
works. The wikipedia example is simple enough to follow (this implementation is based on the wiki's pseudocode). Particulary, this line is very alien to me
def __init__(self, vertices):
self.struct = dict((v, [v, 0]) for v in vertices)
I cannot see what this dict constructor is doing, and my guess is that for every number from 0
to vertices
, a v
is inserted into the dictionary as both a key and a value, but the key has a subset containing v
and an additional 0
to it? I might be very wrong.
Also, as I was comparing the python code
xV = self.struct[xRoot]
yV = self.struct[yRoot]
if xV[1] < yV[1]:
xV[0] = yRoot
elif xV[1] > yV[1]:
yV[0] = xRoot
else:
yV[0] = xRoot
xV[1] += 1
to wikipedia's pseudocode,
if xRoot.rank < yRoot.rank
xRoot.parent := yRoot
else if xRoot.rank > yRoot.rank
yRoot.parent := xRoot
else
yRoot.parent := xRoot
xRoot.rank := xRoot.rank + 1
I was trying to understand how the [0]
's and [1]
's are used. I can only make the connection that the [0]
comes from how we initialised the dictionary struct. Of course, based on mere comparison, it is simple enough to know what they are referring to, but how is this done with the use of 0's and 1's in the struct?
Also, If you need the entire code of which I am talking about, you can find it here.