Skip to content

[mypy] Add/fix type annotations in data_structures/heap/skew_heap.py #5634

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 all 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
22 changes: 13 additions & 9 deletions data_structures/heap/skew_heap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

from __future__ import annotations

from typing import Generic, Iterable, Iterator, TypeVar
from typing import Any, Generic, Iterable, Iterator, TypeVar

T = TypeVar("T")
T = TypeVar("T", bound=bool)


class SkewNode(Generic[T]):
Expand Down Expand Up @@ -51,7 +51,7 @@ class SkewHeap(Generic[T]):
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
Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html

>>> list(SkewHeap([2, 3, 1, 5, 1, 7]))
[1, 1, 2, 3, 5, 7]
Expand All @@ -70,14 +70,16 @@ class SkewHeap(Generic[T]):
"""

def __init__(self, data: Iterable[T] | None = ()) -> None:

"""
>>> sh = SkewHeap([3, 1, 3, 7])
>>> list(sh)
[1, 3, 3, 7]
"""
self._root: SkewNode[T] | None = None
for item in data:
self.insert(item)
if data:
for item in data:
self.insert(item)

def __bool__(self) -> bool:
"""
Expand All @@ -103,7 +105,7 @@ def __iter__(self) -> Iterator[T]:
>>> list(sh)
[1, 3, 3, 7]
"""
result = []
result: list[Any] = []
while self:
result.append(self.pop())

Expand All @@ -127,7 +129,7 @@ def insert(self, value: T) -> None:
"""
self._root = SkewNode.merge(self._root, SkewNode(value))

def pop(self) -> T:
def pop(self) -> T | None:
"""
Pop the smallest value from the heap and return it.

Expand All @@ -146,7 +148,9 @@ def pop(self) -> T:
IndexError: Can't get top element for the empty heap.
"""
result = self.top()
self._root = SkewNode.merge(self._root.left, self._root.right)
self._root = (
SkewNode.merge(self._root.left, self._root.right) if self._root else None
)

return result

Expand All @@ -172,7 +176,7 @@ def top(self) -> T:
raise IndexError("Can't get top element for the empty heap.")
return self._root.value

def clear(self):
def clear(self) -> None:
"""
Clear the heap.

Expand Down