- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathrandomized_heap.py
222 lines (178 loc) · 5.19 KB
/
randomized_heap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python3
from __future__ importannotations
importrandom
fromcollections.abcimportIterable
fromtypingimportAny, Generic, TypeVar
T=TypeVar("T", bound=bool)
classRandomizedHeapNode(Generic[T]):
"""
One node of the randomized heap. Contains the value and references to
two children.
"""
def__init__(self, value: T) ->None:
self._value: T=value
self.left: RandomizedHeapNode[T] |None=None
self.right: RandomizedHeapNode[T] |None=None
@property
defvalue(self) ->T:
"""
Return the value of the node.
>>> rhn = RandomizedHeapNode(10)
>>> rhn.value
10
>>> rhn = RandomizedHeapNode(-10)
>>> rhn.value
-10
"""
returnself._value
@staticmethod
defmerge(
root1: RandomizedHeapNode[T] |None, root2: RandomizedHeapNode[T] |None
) ->RandomizedHeapNode[T] |None:
"""
Merge 2 nodes together.
>>> rhn1 = RandomizedHeapNode(10)
>>> rhn2 = RandomizedHeapNode(20)
>>> RandomizedHeapNode.merge(rhn1, rhn2).value
10
>>> rhn1 = RandomizedHeapNode(20)
>>> rhn2 = RandomizedHeapNode(10)
>>> RandomizedHeapNode.merge(rhn1, rhn2).value
10
>>> rhn1 = RandomizedHeapNode(5)
>>> rhn2 = RandomizedHeapNode(0)
>>> RandomizedHeapNode.merge(rhn1, rhn2).value
0
"""
ifnotroot1:
returnroot2
ifnotroot2:
returnroot1
ifroot1.value>root2.value:
root1, root2=root2, root1
ifrandom.choice([True, False]):
root1.left, root1.right=root1.right, root1.left
root1.left=RandomizedHeapNode.merge(root1.left, root2)
returnroot1
classRandomizedHeap(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/Randomized_meldable_heap
>>> RandomizedHeap([2, 3, 1, 5, 1, 7]).to_sorted_list()
[1, 1, 2, 3, 5, 7]
>>> rh = RandomizedHeap()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
>>> rh.insert(1)
>>> rh.insert(-1)
>>> rh.insert(0)
>>> rh.to_sorted_list()
[-1, 0, 1]
"""
def__init__(self, data: Iterable[T] |None= ()) ->None:
"""
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root: RandomizedHeapNode[T] |None=None
ifdata:
foritemindata:
self.insert(item)
definsert(self, value: T) ->None:
"""
Insert the value into the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.insert(1)
>>> rh.insert(3)
>>> rh.insert(7)
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
self._root=RandomizedHeapNode.merge(self._root, RandomizedHeapNode(value))
defpop(self) ->T|None:
"""
Pop the smallest value from the heap and return it.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.pop()
1
>>> rh.pop()
3
>>> rh.pop()
3
>>> rh.pop()
7
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
result=self.top()
ifself._rootisNone:
returnNone
self._root=RandomizedHeapNode.merge(self._root.left, self._root.right)
returnresult
deftop(self) ->T:
"""
Return the smallest value from the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.top()
3
>>> rh.insert(1)
>>> rh.top()
1
>>> rh.insert(3)
>>> rh.top()
1
>>> rh.insert(7)
>>> rh.top()
1
"""
ifnotself._root:
raiseIndexError("Can't get top element for the empty heap.")
returnself._root.value
defclear(self) ->None:
"""
Clear the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.clear()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
self._root=None
defto_sorted_list(self) ->list[Any]:
"""
Returns sorted list containing all the values in the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.to_sorted_list()
[1, 3, 3, 7]
"""
result= []
whileself:
result.append(self.pop())
returnresult
def__bool__(self) ->bool:
"""
Check if the heap is not empty.
>>> rh = RandomizedHeap()
>>> bool(rh)
False
>>> rh.insert(1)
>>> bool(rh)
True
>>> rh.clear()
>>> bool(rh)
False
"""
returnself._rootisnotNone
if__name__=="__main__":
importdoctest
doctest.testmod()