Answers for "python union calculate"

2

union find python

class UnionFind:
    def __init__(self) -> None:
        super().__init__()
        self.representor = {}

    def make_set(self, key):
        self.representor[key] = key

    def find(self, key):
        return self.representor[key]

    def union(self, x, y):
        x_r, y_r = self.find(x), self.find(y)
        for k, r in self.representor.items():
            if r == y_r:
                self.representor[k] = x_r
Posted by: Guest on October-01-2021
1

python union find

class DisjointSet:
    def __init__(self, n):
        self.data = list(range(n))
        self.size = n

    def find(self, index):
        return self.data[index]


	def union(self, x, y):
    	x, y = self.find(x), self.find(y)

	    if x == y:
    	    return

	    for i in range(self.size):
    	    if self.find(i) == y:
        	    self.data[i] = x


    @property
    def length(self):
        return len(set(self.data))




disjoint = DisjointSet(10)

disjoint.union(0, 1)
disjoint.union(1, 2)
disjoint.union(2, 3)
disjoint.union(4, 5)
disjoint.union(5, 6)
disjoint.union(6, 7)
disjoint.union(8, 9)

print(disjoint.data)
print(disjoint.length)


# [0, 0, 0, 0, 4, 4, 4, 4, 8, 8]
# 3
Posted by: Guest on September-28-2020

Python Answers by Framework

Browse Popular Code Answers by Language