-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add union-find. Still planning the best way to test this.
- Loading branch information
1 parent
e77583c
commit 317faa9
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
#! /usr/bin/env python3 | ||
|
||
class DataNode(object): | ||
|
||
def __init__(self, data, parent=None) | ||
self.data = data | ||
self.parent = parent | ||
parent_weight = parent.weight if parent else 0 | ||
self.weight = 1 + parent_weight | ||
|
||
def find(self): | ||
""" | ||
Find the ultimate parent of this node. | ||
Haha it is "recursive". I wonder if this is good. | ||
""" | ||
if self.parent: | ||
return self.parent.find() | ||
else: | ||
return self | ||
|
||
def union(self, other_node): | ||
if self.weight > other_node.weight: | ||
other_parent = other_node.find() | ||
other_parent.parent = self.parent | ||
other_parent.weight += self.weight | ||
else: | ||
self.parent = other_node.find() | ||
self.weight += other_node.weight | ||
|
||
class UnionFind(object): | ||
""" | ||
A disjointed set structure. This assumes that the data added to it cannot | ||
be overwritten. | ||
""" | ||
|
||
def __init__(self): | ||
self.data2node = {} | ||
|
||
def add_object(self, data): | ||
if self.data2node.get(data): | ||
raise Exception("%s data already exists. Can't overwrite." % data) | ||
else: | ||
self.data2node[data] = DataNode(data) | ||
|
||
def make_equal(self, d1, d2): | ||
if not self.data2node.get(d1): | ||
self.add_object(d1) | ||
|
||
if not self.data2node.get(d2): | ||
self.add_object(d2) | ||
|
||
self.data2node[d1].union(self.data2node[d2]) | ||
|
||
def is_equal(self, d1, d2): | ||
""" | ||
Again, only works because of the assumption that data here cannot be | ||
overwritten. | ||
Also assumes that the data given to this object can be compared. | ||
""" | ||
return d1.find().data == d2.find().data |