Skip to content

Commit 99983c9

Browse files
authored
[mypy] Add/fix type annotations in data_structures/heap/skew_heap.py (TheAlgorithms#5634)
* Add abstract base class Comparable * [mypy] Fix type annotations (strict mode) * Fix a typo * Remove Comparable class and set bound to bool
1 parent 21c99d2 commit 99983c9

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

data_structures/heap/skew_heap.py

+13-9
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
from __future__ import annotations
44

5-
from typing import Generic, Iterable, Iterator, TypeVar
5+
from typing import Any, Generic, Iterable, Iterator, TypeVar
66

7-
T = TypeVar("T")
7+
T = TypeVar("T", bound=bool)
88

99

1010
class SkewNode(Generic[T]):
@@ -51,7 +51,7 @@ class SkewHeap(Generic[T]):
5151
values. Both operations take O(logN) time where N is the size of the
5252
structure.
5353
Wiki: https://en.wikipedia.org/wiki/Skew_heap
54-
Visualisation: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html
54+
Visualization: https://www.cs.usfca.edu/~galles/visualization/SkewHeap.html
5555
5656
>>> list(SkewHeap([2, 3, 1, 5, 1, 7]))
5757
[1, 1, 2, 3, 5, 7]
@@ -70,14 +70,16 @@ class SkewHeap(Generic[T]):
7070
"""
7171

7272
def __init__(self, data: Iterable[T] | None = ()) -> None:
73+
7374
"""
7475
>>> sh = SkewHeap([3, 1, 3, 7])
7576
>>> list(sh)
7677
[1, 3, 3, 7]
7778
"""
7879
self._root: SkewNode[T] | None = None
79-
for item in data:
80-
self.insert(item)
80+
if data:
81+
for item in data:
82+
self.insert(item)
8183

8284
def __bool__(self) -> bool:
8385
"""
@@ -103,7 +105,7 @@ def __iter__(self) -> Iterator[T]:
103105
>>> list(sh)
104106
[1, 3, 3, 7]
105107
"""
106-
result = []
108+
result: list[Any] = []
107109
while self:
108110
result.append(self.pop())
109111

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

130-
def pop(self) -> T:
132+
def pop(self) -> T | None:
131133
"""
132134
Pop the smallest value from the heap and return it.
133135
@@ -146,7 +148,9 @@ def pop(self) -> T:
146148
IndexError: Can't get top element for the empty heap.
147149
"""
148150
result = self.top()
149-
self._root = SkewNode.merge(self._root.left, self._root.right)
151+
self._root = (
152+
SkewNode.merge(self._root.left, self._root.right) if self._root else None
153+
)
150154

151155
return result
152156

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

175-
def clear(self):
179+
def clear(self) -> None:
176180
"""
177181
Clear the heap.
178182

0 commit comments

Comments
 (0)