# We define a class for the nodes of disjoint sets. class Node: # The __init__ function defines the initial values of a new node. The # label value must be passed to a new node as an argument. We also add # the attributes parent and rank. def __init__(self, label): self.label = label self.parent = self self.rank = 0 # Next, we define some functions to works with our class. We will start # with a function to make a new set. def make_set(node): # We set the parent of the node to itself since it is now in a set by # itself. Note the use of the dot operator. node.parent = node rank = 0 # Now, we write a function to find the representative of a node. def find_set(node): # Next, we write a function that links the representatives of two sets. def link(node1, node2): # Finally, we add a function to join two sets. def union(node1, node2): # Now, we write our main function to run some test cases. def main(): # We import the string library for later (test cases). import string # This test case should look familiar. It is a problem from the quiz. # First, we list all of the elements. label_list = list(string.ascii_lowercase[:8]) # Then, we list the edges in the form of tuples. edge_list = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('b', 'c'), ('b', 'f'), ('d', 'g')] # (1) Initialize nodes # (2) We build our sets based on the given edges. for edge in edge_list: # sequence of Union() # (3) We print our results. An example of printing for label in node = print('Element {0} has label {1}, '.format(label, node.label) + 'parent {0}, and representative '.format(node.parent.label) + '{0}.'.format(find_set(node).label)) # Run test cases as long as this isn't used as a module. if __name__ == '__main__': main()