Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DHeap added #118

Merged
merged 7 commits into from
Mar 11, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions pydatastructs/trees/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@

from .heaps import (
BinaryHeap,
TernaryHeap,
DHeap,
BinomialHeap
)
__all__.extend(heaps.__all__)
173 changes: 148 additions & 25 deletions pydatastructs/trees/heaps.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@

__all__ = [
'BinaryHeap',
'TernaryHeap',
'DHeap',
'BinomialHeap'
]

Expand All @@ -14,9 +16,10 @@ class Heap(object):
"""
pass

class BinaryHeap(Heap):

class DHeap(Heap):
"""
Represents Binary Heap.
Represents D-ary Heap.

Parameters
==========
Expand All @@ -26,7 +29,6 @@ class BinaryHeap(Heap):
List/tuple of initial elements in Heap.

heap_property : str
The property of binary heap.
If the key stored in each node is
either greater than or equal to
the keys in the node's children
Expand All @@ -41,8 +43,8 @@ class BinaryHeap(Heap):
Examples
========

>>> from pydatastructs.trees.heaps import BinaryHeap
>>> min_heap = BinaryHeap(heap_property="min")
>>> from pydatastructs.trees.heaps import DHeap
>>> min_heap = DHeap(heap_property="min", d=3)
>>> min_heap.insert(1, 1)
>>> min_heap.insert(5, 5)
>>> min_heap.insert(7, 7)
Expand All @@ -52,7 +54,7 @@ class BinaryHeap(Heap):
>>> min_heap.extract().key
4

>>> max_heap = BinaryHeap(heap_property='max')
>>> max_heap = DHeap(heap_property='max', d=2)
>>> max_heap.insert(1, 1)
>>> max_heap.insert(5, 5)
>>> max_heap.insert(7, 7)
Expand All @@ -65,13 +67,14 @@ class BinaryHeap(Heap):
References
==========

.. [1] https://en.m.wikipedia.org/wiki/Binary_heap
.. [1] https://en.wikipedia.org/wiki/D-ary_heap
"""
__slots__ = ['_comp', 'heap', 'heap_property', '_last_pos_filled']
__slots__ = ['_comp', 'heap', 'd', 'heap_property', '_last_pos_filled']

def __new__(cls, elements=None, heap_property="min"):
def __new__(cls, elements=None, heap_property="min", d=4):
obj = Heap.__new__(cls)
obj.heap_property = heap_property
obj.d = d
if heap_property == "min":
obj._comp = lambda key_parent, key_child: key_parent <= key_child
elif heap_property == "max":
Expand All @@ -88,8 +91,8 @@ def __new__(cls, elements=None, heap_property="min"):
def _build(self):
for i in range(self._last_pos_filled + 1):
self.heap[i].left, self.heap[i].right = \
2*i + 1, 2*i + 2
for i in range((self._last_pos_filled + 1)//2, -1, -1):
self.d*i + 1, self.d*i + self.d
for i in range((self._last_pos_filled + 1)//self.d, -1, -1):
self._heapify(i)

def _swap(self, idx1, idx2):
Expand All @@ -103,23 +106,22 @@ def _swap(self, idx1, idx2):
def _heapify(self, i):
while True:
target = i
l = 2*i + 1
r = 2*i + 2
l = self.d*i + 1
r = self.d*i + self.d

if l <= self._last_pos_filled:
target = l if self._comp(self.heap[l].key, self.heap[target].key) \
else i
if r <= self._last_pos_filled:
target = r if self._comp(self.heap[r].key, self.heap[target].key) \
else target
for j in range(l, r+1):
if j <= self._last_pos_filled:
target = j if self._comp(self.heap[j].key, self.heap[target].key) \
else target
else:
break

if target != i:
self._swap(target, i)
i = target
else:
break


def insert(self, key, data):
"""
Insert a new element to the heap according to heap property.
Expand All @@ -141,10 +143,10 @@ def insert(self, key, data):
self.heap.append(new_node)
self._last_pos_filled += 1
i = self._last_pos_filled
self.heap[i].left, self.heap[i].right = 2*i + 1, 2*i + 2
self.heap[i].left, self.heap[i].right = self.d*i + 1, self.d*i + self.d
czgdp1807 marked this conversation as resolved.
Show resolved Hide resolved

while True:
parent = (i - 1)//2
parent = (i - 1)//self.d
if i == 0 or self._comp(self.heap[parent].key, self.heap[i].key):
break
else:
Expand Down Expand Up @@ -180,12 +182,133 @@ def __str__(self):
to_be_printed = ['' for i in range(self._last_pos_filled + 1)]
for i in range(self._last_pos_filled + 1):
node = self.heap[i]
to_be_printed[i] = (node.left if node.left <= self._last_pos_filled else None,
node.key, node.data,
node.right if node.right <= self._last_pos_filled else None)
if node.left <= self._last_pos_filled:
if node.right <= self._last_pos_filled:
children = [x for x in range(node.left, node.right + 1)]
else:
children = [x for x in range(node.left, self._last_pos_filled + 1)]
else:
children = []
to_be_printed[i] = (node.key, node.data, children)
return str(to_be_printed)


class BinaryHeap(DHeap):
"""
Represents Binary Heap.

Parameters
==========

elements : list, tuple
Optional, by default 'None'.
List/tuple of initial elements in Heap.

heap_property : str
If the key stored in each node is
either greater than or equal to
the keys in the node's children
then pass 'max'.
If the key stored in each node is
either less than or equal to
the keys in the node's children
then pass 'min'.
By default, the heap property is
set to 'min'.

Examples
========

>>> from pydatastructs.trees.heaps import BinaryHeap
>>> min_heap = BinaryHeap(heap_property="min")
>>> min_heap.insert(1, 1)
>>> min_heap.insert(5, 5)
>>> min_heap.insert(7, 7)
>>> min_heap.extract().key
1
>>> min_heap.insert(4, 4)
>>> min_heap.extract().key
4

>>> max_heap = BinaryHeap(heap_property='max')
>>> max_heap.insert(1, 1)
>>> max_heap.insert(5, 5)
>>> max_heap.insert(7, 7)
>>> max_heap.extract().key
7
>>> max_heap.insert(6, 6)
>>> max_heap.extract().key
6

References
==========

.. [1] https://en.m.wikipedia.org/wiki/Binary_heap
"""
def __new__(cls, elements=None, heap_property="min"):
obj = DHeap.__new__(cls, elements, heap_property, 2)
return obj


class TernaryHeap(DHeap):
"""
Represents Ternary Heap.

Parameters
==========

elements : list, tuple
Optional, by default 'None'.
List/tuple of initial elements in Heap.

heap_property : str
If the key stored in each node is
either greater than or equal to
the keys in the node's children
then pass 'max'.
If the key stored in each node is
either less than or equal to
the keys in the node's children
then pass 'min'.
By default, the heap property is
set to 'min'.

Examples
========

>>> from pydatastructs.trees.heaps import TernaryHeap
>>> min_heap = TernaryHeap(heap_property="min")
>>> min_heap.insert(1, 1)
>>> min_heap.insert(5, 5)
>>> min_heap.insert(7, 7)
>>> min_heap.insert(3, 3)
>>> min_heap.extract().key
1
>>> min_heap.insert(4, 4)
>>> min_heap.extract().key
3

>>> max_heap = TernaryHeap(heap_property='max')
>>> max_heap.insert(1, 1)
>>> max_heap.insert(5, 5)
>>> max_heap.insert(7, 7)
>>> min_heap.insert(3, 3)
>>> max_heap.extract().key
7
>>> max_heap.insert(6, 6)
>>> max_heap.extract().key
6

References
==========

.. [1] https://en.wikipedia.org/wiki/D-ary_heap
czgdp1807 marked this conversation as resolved.
Show resolved Hide resolved
"""
def __new__(cls, elements=None, heap_property="min"):
obj = DHeap.__new__(cls, elements, heap_property, 3)
return obj


class BinomialHeap(Heap):
"""
Represents binomial heap.
Expand Down
88 changes: 83 additions & 5 deletions pydatastructs/trees/tests/test_heaps.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pydatastructs.trees.heaps import BinaryHeap, BinomialHeap
from pydatastructs.trees.heaps import BinaryHeap, TernaryHeap, BinomialHeap, DHeap
from pydatastructs.miscellaneous_data_structures.binomial_trees import BinomialTree
from pydatastructs.utils.misc_util import TreeNode, BinomialTreeNode
from pydatastructs.utils.raises_util import raises
Expand All @@ -20,10 +20,10 @@ def test_BinaryHeap():
max_heap.insert(2, 2)
max_heap.insert(7, 7)
assert str(max_heap) == \
("[(1, 100, 100, 2), (3, 19, 19, 4), "
"(5, 36, 36, 6), (7, 17, 17, 8), "
"(None, 3, 3, None), (None, 25, 25, None), "
"(None, 1, 1, None), (None, 2, 2, None), (None, 7, 7, None)]")
("[(100, 100, [1, 2]), (19, 19, [3, 4]), "
"(36, 36, [5, 6]), (17, 17, [7, 8]), "
"(3, 3, []), (25, 25, []), (1, 1, []), "
"(2, 2, []), (7, 7, [])]")

expected_extracted_element = max_heap.heap[0].key
assert max_heap.extract().key == expected_extracted_element
Expand All @@ -40,13 +40,91 @@ def test_BinaryHeap():
TreeNode(17, 17), TreeNode(19, 19), TreeNode(36, 36)
]
min_heap = BinaryHeap(elements = elements, heap_property="min")
assert min_heap.extract().key == 1

expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
sorted_elements = [min_heap.extract().key for _ in range(8)]
assert expected_sorted_elements == sorted_elements

def test_TernaryHeap():
max_heap = TernaryHeap(heap_property="max")
assert max_heap.extract() is None
max_heap.insert(100, 100)
max_heap.insert(19, 19)
max_heap.insert(36, 36)
max_heap.insert(17, 17)
max_heap.insert(3, 3)
max_heap.insert(25, 25)
max_heap.insert(1, 1)
max_heap.insert(2, 2)
max_heap.insert(7, 7)
assert str(max_heap) == \
('[(100, 100, [1, 2, 3]), (25, 25, [4, 5, 6]), '
'(36, 36, [7, 8]), (17, 17, []), '
'(3, 3, []), (19, 19, []), (1, 1, []), '
'(2, 2, []), (7, 7, [])]')

assert max_heap.extract().key == 100

expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
sorted_elements = []
for _ in range(8):
sorted_elements.append(max_heap.extract().key)
assert expected_sorted_elements == sorted_elements

elements = [
TreeNode(7, 7), TreeNode(25, 25), TreeNode(100, 100),
TreeNode(1, 1), TreeNode(2, 2), TreeNode(3, 3),
TreeNode(17, 17), TreeNode(19, 19), TreeNode(36, 36)
]
min_heap = TernaryHeap(elements=elements, heap_property="min")
expected_extracted_element = min_heap.heap[0].key
assert min_heap.extract().key == expected_extracted_element

expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
sorted_elements = [min_heap.extract().key for _ in range(8)]
assert expected_sorted_elements == sorted_elements

def test_DHeap():
assert raises(ValueError, lambda: DHeap(heap_property="none", d=4))
max_heap = DHeap(heap_property="max", d=5)
assert max_heap.extract() is None
max_heap.insert(100, 100)
max_heap.insert(19, 19)
max_heap.insert(36, 36)
max_heap.insert(17, 17)
max_heap.insert(3, 3)
max_heap.insert(25, 25)
max_heap.insert(1, 1)
max_heap = DHeap(max_heap.heap, heap_property="max", d=4)
max_heap.insert(2, 2)
max_heap.insert(7, 7)
assert str(max_heap) == \
('[(100, 100, [1, 2, 3, 4]), (25, 25, [5, 6, 7, 8]), '
'(36, 36, []), (17, 17, []), (3, 3, []), (19, 19, []), '
'(1, 1, []), (2, 2, []), (7, 7, [])]')

expected_extracted_element = max_heap.heap[0].key
assert max_heap.extract().key == expected_extracted_element

expected_sorted_elements = [36, 25, 19, 17, 7, 3, 2, 1]
sorted_elements = []
for _ in range(8):
sorted_elements.append(max_heap.extract().key)
assert expected_sorted_elements == sorted_elements

elements = [
TreeNode(7, 7), TreeNode(25, 25), TreeNode(100, 100),
TreeNode(1, 1), TreeNode(2, 2), TreeNode(3, 3),
TreeNode(17, 17), TreeNode(19, 19), TreeNode(36, 36)
]
min_heap = DHeap(elements=elements, heap_property="min")
assert min_heap.extract().key == 1

expected_sorted_elements = [2, 3, 7, 17, 19, 25, 36, 100]
sorted_elements = [min_heap.extract().key for _ in range(8)]
assert expected_sorted_elements == sorted_elements

def test_BinomialHeap():

# Corner cases
Expand Down