What I still have is largely based on p. 571, An Introduction to Algorithms, by Cormen et al.
I have a Node class in python that represents a collection:
class Node: def __init__(self, parent, rank = 0): self.parent = parent self.rank = rank
This implementation will use List nodes as a forest (I am open to better ways to store sets).
Initialize() returns a list of nodes that I will store in the set variable, and go to other functions.
Find searches the forest for the value and returns the set in which it appears. I decided to use for s in range(len(set)): so that in recursion I could compress the list of sets passed to set[s:] .
def Find(set, value): for s in range(len(set)): if value != set[s].parent: set[s].parent = Find(set[s:], set[s].parent) return set[s]
Merge brings together sets in the forest, discovering them and contributing to a higher level set.
def Merge(set, value1, value2): set_val_1 = Find(set, value1) set_val_2 = Find(set, value2) if set_val_1.rank > set_val_2.rank: set_val_2.parent = set_val_1 else: set_val_1.parent = set_val_2 if set_val_1.rank == set_val_2.rank: set_val_2.rank += 1
I get some errors when I do Find and Merge s, namely Find does not return the correct set, and therefore I'm not sure that Merge working fine. I would appreciate some help to make sure that the functions performed correctly.
python merge find disjoint-sets
Jordan
source share