Question: d = DisjointForests ( 1 0 ) for i in range ( 1 0 ) : d . make _ set ( i ) for
d DisjointForests
for i in range:
dmakeseti
for i in range:
assert dfindi i f'Failed: Find on i must return i back'
dunion
dunion
assertdfind dfind and have been unioned together'
assertdfind dfind and have been unioned together'
assertdfind dfind and should be in different trees'
assertdgetrank and dgetrank or
dgetrank and dgetrank 'one of the nodes or must have rank
assertdgetrank and dgetrank or
dgetrank and dgetrank 'one of the nodes or must have rank
dunion
assertdfind dfind and must be in the same set in the family.
dunion
dunion
dunion
dunion
assertdfind dfind and must be in the same set in the family'
assertdfind dfind and must be in the same set in the family'
printAll tests passed: points.
AssertionError Traceback most recent call last
We will first complete an implemention of a unionfind data structure with rank compression.
class DisjointForests:
def self n:
assert n Empty disjoint forest is disallowed'
self.n n
self.parents Nonen
self.rank NonenConvert the disjoint forest structure into a dictionary ddi maps to each elements which belongs to the tree corresponding to idef dictionaryofsetsself:
d
for i in rangeselfn:
if self.isrepresentativei:
di seti
for j in rangeselfn:
if self.parentsj None:
root self.findj
assert root in d
drootaddj
return d
def makesetself j:
assert j self.n
assert self.parentsj None, 'You are calling makeset on an element multiple times not allowed.
self.parentsj j
self.rankj
def isrepresentativeself j:
return self.parentsj j
def getrankself j:
return self.rankjImplement the find algorithm for a node j in the set.Implement the "rank compression" strategy by making alldef findself j:
assert j self.n
assert self.parentsj None, 'You are calling find on an element that is not part of the family yet. Pleaif selfparentsj j:
return j
return self.findselfparentsjCompute union of j and jIf they are not the same, thenchild of the higher ranked root.def unionself j j:
assert j self.n
assert j self.n
assert self.parentsj None
assert self.parentsj Nonejrep self.findselfparentsj
jrep self.findselfparentsj
jrank self.getrankjrep
jrank self.getrankjrep
if jrep jrep:
return
ifjrep jrep:
self.parentsjrep jrep
elifjrep jrep:
self.parentsjrep jrep
else:
self.parentsjrep jrep
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
