-
-
Notifications
You must be signed in to change notification settings - Fork 46.9k
Add skew heap data structure. #3238
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
35148b8
Add skew heap data structure.
Phil9l 8bb42d1
fixup! Add skew heap data structure.
Phil9l 441fa13
fixup! Add skew heap data structure.
Phil9l 026933b
fixup! Add skew heap data structure.
Phil9l c5acb2c
Add tests.
Phil9l e447ba1
Merge branch 'master' of github.com:TheAlgorithms/Python into skew-heap
Phil9l a3e76eb
Add __iter__ method.
Phil9l fc2a9c4
fixup! Add __iter__ method.
Phil9l File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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,120 @@ | ||
#!/usr/bin/env python3 | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Generic, Iterable, List, Optional, TypeVar | ||
|
||
__all__ = ["SkewHeap"] | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
class SkewNode(Generic[T]): | ||
"""One node of the skew heap. Contains the value and references to two children.""" | ||
|
||
def __init__(self, value: T) -> None: | ||
self._value: T = value | ||
self.left: Optional[SkewNode[T]] = None | ||
self.right: Optional[SkewNode[T]] = None | ||
|
||
@property | ||
def value(self) -> T: | ||
"""Return the value of the node.""" | ||
return self._value | ||
|
||
@staticmethod | ||
def merge( | ||
root1: Optional[SkewNode[T]], root2: Optional[SkewNode[T]] | ||
) -> Optional[SkewNode[T]]: | ||
"""Merge 2 nodes together.""" | ||
if not root1: | ||
return root2 | ||
|
||
if not root2: | ||
return root1 | ||
|
||
if root1.value > root2.value: | ||
root1, root2 = root2, root1 | ||
|
||
result = root1 | ||
temp = root1.right | ||
result.right = root1.left | ||
result.left = SkewNode.merge(temp, root2) | ||
|
||
return result | ||
|
||
|
||
class SkewHeap(Generic[T]): | ||
""" | ||
A data structure that allows inserting a new value and to pop the smallest | ||
values. Both operations take O(logN) time where N is the size of the structure. | ||
- Wiki: https://en.wikipedia.org/wiki/Skew_heap | ||
- Visualisation: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html | ||
|
||
>>> SkewHeap.from_list([2, 3, 1, 5, 1, 7]).to_sorted_list() | ||
[1, 1, 2, 3, 5, 7] | ||
|
||
>>> sh = SkewHeap() | ||
>>> sh.insert(1) | ||
Phil9l marked this conversation as resolved.
Show resolved
Hide resolved
|
||
>>> sh.top() | ||
1 | ||
>>> sh.insert(0) | ||
>>> sh.pop() | ||
0 | ||
>>> sh.pop() | ||
1 | ||
>>> sh.top() | ||
Traceback (most recent call last): | ||
... | ||
AttributeError: Can't get top element for the empty heap. | ||
""" | ||
|
||
def __init__(self) -> None: | ||
self._root: Optional[SkewNode[T]] = None | ||
|
||
def insert(self, value: T) -> None: | ||
"""Insert the value into the heap.""" | ||
self._root = SkewNode.merge(self._root, SkewNode(value)) | ||
|
||
def pop(self) -> T: | ||
"""Pop the smallest value from the heap and return it.""" | ||
result = self.top() | ||
self._root = SkewNode.merge(self._root.left, self._root.right) | ||
|
||
return result | ||
|
||
def top(self) -> T: | ||
"""Return the smallest value from the heap.""" | ||
if not self._root: | ||
raise AttributeError("Can't get top element for the empty heap.") | ||
return self._root.value | ||
|
||
def clear(self): | ||
self._root = None | ||
|
||
@staticmethod | ||
def from_list(data: Iterable[T]) -> SkewHeap[T]: | ||
"""Get the sorted list from the heap. Heap will be cleared afterwards.""" | ||
result = SkewHeap() | ||
for item in data: | ||
result.insert(item) | ||
|
||
return result | ||
|
||
def to_sorted_list(self) -> List[T]: | ||
Phil9l marked this conversation as resolved.
Show resolved
Hide resolved
|
||
"""Returns sorted list containing all the values in the heap.""" | ||
result = [] | ||
while self: | ||
result.append(self.pop()) | ||
|
||
return result | ||
|
||
def __bool__(self) -> bool: | ||
"""Check if the heap is not empty.""" | ||
return self._root is not None | ||
|
||
|
||
if __name__ == "__main__": | ||
import doctest | ||
|
||
doctest.testmod() |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.