Skip to content

Commit

Permalink
Fix adding empty set to disjoint sets
Browse files Browse the repository at this point in the history
  • Loading branch information
ref-humbold committed Feb 25, 2024
1 parent 2bbd433 commit 56a4599
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
12 changes: 7 additions & 5 deletions algolib/structures/disjoint_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,15 @@ def add(self, elements: Iterable[_T], represent: Optional[_T] = None):
if element in self:
raise ValueError(f"Value {element} already present.")

set_represent = self._represents[represent] if represent is not None else elements_tuple[0]
if len(elements_tuple) > 0:
set_represent = self._represents[represent] if represent is not None else \
elements_tuple[0]

for element in elements_tuple:
self._represents[element] = set_represent
for element in elements_tuple:
self._represents[element] = set_represent

if represent is None:
self._count += 1
if represent is None:
self._count += 1

return self

Expand Down
12 changes: 12 additions & 0 deletions tests/structures/test_disjoint_sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,12 @@ def test__op_iadd__when_empty__then_new_set(self):

assert_that(self.test_object).is_length(1)

def test__op_iadd__when_empty_new_elements__then_no_changes(self):
# when
self.test_object += []
# then
assert_that(self.test_object).is_length(len(self.numbers))

def test__op_iadd__when_new_elements__then_new_set(self):
# when
self.test_object += self.absent
Expand Down Expand Up @@ -120,6 +126,12 @@ def function(elements):
# endregion
# region add

def test__add__when_empty_new_elements_to_present_represent__then_no_changes(self):
# when
self.test_object.add([], self.present[0])
# then
assert_that(self.test_object).is_length(len(self.numbers))

def test__add__when_new_elements_to_present_represent__then_added_to_existing_set(self):
# given
represent = self.present[0]
Expand Down

0 comments on commit 56a4599

Please sign in to comment.