2
2
3
3
from __future__ import annotations
4
4
5
- from typing import Generic , Iterable , Iterator , TypeVar
5
+ from typing import Any , Generic , Iterable , Iterator , TypeVar
6
6
7
- T = TypeVar ("T" )
7
+ T = TypeVar ("T" , bound = bool )
8
8
9
9
10
10
class SkewNode (Generic [T ]):
@@ -51,7 +51,7 @@ class SkewHeap(Generic[T]):
51
51
values. Both operations take O(logN) time where N is the size of the
52
52
structure.
53
53
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
55
55
56
56
>>> list(SkewHeap([2, 3, 1, 5, 1, 7]))
57
57
[1, 1, 2, 3, 5, 7]
@@ -70,14 +70,16 @@ class SkewHeap(Generic[T]):
70
70
"""
71
71
72
72
def __init__ (self , data : Iterable [T ] | None = ()) -> None :
73
+
73
74
"""
74
75
>>> sh = SkewHeap([3, 1, 3, 7])
75
76
>>> list(sh)
76
77
[1, 3, 3, 7]
77
78
"""
78
79
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 )
81
83
82
84
def __bool__ (self ) -> bool :
83
85
"""
@@ -103,7 +105,7 @@ def __iter__(self) -> Iterator[T]:
103
105
>>> list(sh)
104
106
[1, 3, 3, 7]
105
107
"""
106
- result = []
108
+ result : list [ Any ] = []
107
109
while self :
108
110
result .append (self .pop ())
109
111
@@ -127,7 +129,7 @@ def insert(self, value: T) -> None:
127
129
"""
128
130
self ._root = SkewNode .merge (self ._root , SkewNode (value ))
129
131
130
- def pop (self ) -> T :
132
+ def pop (self ) -> T | None :
131
133
"""
132
134
Pop the smallest value from the heap and return it.
133
135
@@ -146,7 +148,9 @@ def pop(self) -> T:
146
148
IndexError: Can't get top element for the empty heap.
147
149
"""
148
150
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
+ )
150
154
151
155
return result
152
156
@@ -172,7 +176,7 @@ def top(self) -> T:
172
176
raise IndexError ("Can't get top element for the empty heap." )
173
177
return self ._root .value
174
178
175
- def clear (self ):
179
+ def clear (self ) -> None :
176
180
"""
177
181
Clear the heap.
178
182
0 commit comments