Question: * * Please only answer the #your code here * * class DisjointForests: def _ _ init _ _ ( self , n ) :
Please only answer the #your code here
class DisjointForests:
def initself n:
assert n Empty disjoint forest is disallowed'
self.n n
self.parents Nonen
self.rank Nonen
# Function: dictionaryofsets
# Convert the disjoint forest structure into a dictionary d
# wherein d has an entry for each representative i
# di maps to each elements which belongs to the tree corresponding to i
# in the disjoint forest.
def 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.rankj
# Function: find
# Implement the find algorithm for a node j in the set.
# Repeatedly traverse the parent pointer until we reach a root.
# Implement the "rank compression" strategy by making all
# nodes along path from j to the root point directly to the root.
def 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. Please call makeset first.
# your code here
# Function : union
# Compute union of j and j
# First do a find to get to the representatives of j and j
# If they are not the same, then
# implement union using the rank strategy I.e lower rank root becomes
# child of the higher ranked root.
# break ties by making the first argument js root the parent.
def unionself j j:
assert j self.n
assert j self.n
assert self.parentsj None
assert self.parentsj None
# your code here
Test:
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.
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
