forked from exaloop/codon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathheapq.codon
More file actions
345 lines (323 loc) · 11.1 KB
/
heapq.codon
File metadata and controls
345 lines (323 loc) · 11.1 KB
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# Copyright (C) 2022-2023 Exaloop Inc. <https://exaloop.io>
# 'heap' is a heap at all indices >= startpos, except possibly for pos. pos
# is the index of a leaf with a possibly out-of-order value. Restore the
# heap invariant.
def _siftdown(heap: List[T], startpos: int, pos: int, T: type):
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if newitem < parent:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup(heap: List[T], pos: int, T: type):
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the smaller child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of smaller child.
rightpos = childpos + 1
if rightpos < endpos and not heap[childpos] < heap[rightpos]:
childpos = rightpos
# Move the smaller child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown(heap, startpos, pos)
def _siftdown_max(heap: List[T], startpos: int, pos: int, T: type):
"Maxheap variant of _siftdown"
newitem = heap[pos]
# Follow the path to the root, moving parents down until finding a place
# newitem fits.
while pos > startpos:
parentpos = (pos - 1) >> 1
parent = heap[parentpos]
if parent < newitem:
heap[pos] = parent
pos = parentpos
continue
break
heap[pos] = newitem
def _siftup_max(heap: List[T], pos: int, T: type):
"Maxheap variant of _siftup"
endpos = len(heap)
startpos = pos
newitem = heap[pos]
# Bubble up the larger child until hitting a leaf.
childpos = 2 * pos + 1 # leftmost child position
while childpos < endpos:
# Set childpos to index of larger child.
rightpos = childpos + 1
if rightpos < endpos and not heap[rightpos] < heap[childpos]:
childpos = rightpos
# Move the larger child up.
heap[pos] = heap[childpos]
pos = childpos
childpos = 2 * pos + 1
# The leaf at pos is empty now. Put newitem there, and bubble it up
# to its final resting place (by sifting its parents down).
heap[pos] = newitem
_siftdown_max(heap, startpos, pos)
def heappush(heap: List[T], item: T, T: type):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown(heap, 0, len(heap) - 1)
def heappop(heap: List[T], T: type) -> T:
"""Pop the smallest item off the heap, maintaining the heap invariant."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup(heap, 0)
return returnitem
return lastelt
def heapreplace(heap: List[T], item: T, T: type) -> T:
"""
Pop and return the current smallest value, and add the new item.
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed-size heap. Note that the value
returned may be larger than item! That constrains reasonable uses of
this routine unless written as part of a conditional replacement:
``if item > heap[0]: item = heapreplace(heap, item)``.
"""
returnitem = heap[0] # raises appropriate IndexError if heap is empty
heap[0] = item
_siftup(heap, 0)
return returnitem
def heappushpop(heap: List[T], item: T, T: type) -> T:
"""Fast version of a heappush followed by a heappop."""
if heap and heap[0] < item:
item, heap[0] = heap[0], item
_siftup(heap, 0)
return item
def heapify(x: List[T], T: type):
"""Transform list into a heap, in-place, in $O(len(x))$ time."""
n = len(x)
# Transform bottom-up. The largest index there's any point to looking at
# is the largest with a child index in-range, so must have 2*i + 1 < n,
# or i < (n-1)/2. If n is even = 2*j, this is (2*j-1)/2 = j-1/2 so
# j-1 is the largest, which is n//2 - 1. If n is odd = 2*j+1, this is
# (2*j+1-1)/2 = j so j-1 is the largest, and that's again n//2-1.
for i in reversed(range(n // 2)):
_siftup(x, i)
def _heappop_max(heap: List[T], T: type) -> T:
"""Maxheap version of a heappop."""
lastelt = heap.pop() # raises appropriate IndexError if heap is empty
if heap:
returnitem = heap[0]
heap[0] = lastelt
_siftup_max(heap, 0)
return returnitem
return lastelt
def _heapreplace_max(heap: List[T], item: T, T: type) -> T:
"""Maxheap version of a heappop followed by a heappush."""
returnitem = heap[0] # raises appropriate IndexError if heap is empty
heap[0] = item
_siftup_max(heap, 0)
return returnitem
def _heapify_max(x: List[T], T: type):
"""Transform list into a maxheap, in-place, in O(len(x)) time."""
n = len(x)
for i in reversed(range(n // 2)):
_siftup_max(x, i)
def nsmallest(n: int, iterable: Generator[T], key=Optional[int](), T: type) -> List[T]:
"""Find the n smallest elements in a dataset.
Equivalent to: sorted(iterable, key=key)[:n]
"""
if n == 1:
v = List(1)
for a in iterable:
if not v:
v.append(a)
else:
if not isinstance(key, Optional):
if key(a) < key(v[0]):
v[0] = a
elif a < v[0]:
v[0] = a
return v
# When key is none, use simpler decoration
if isinstance(key, Optional):
it = iter(iterable)
# put the range(n) first so that zip() doesn't
# consume one too many elements from the iterator
result = List(n)
done = False
for i in range(n):
if it.done():
done = True
break
result.append((it.next(), i))
if not result:
it.destroy()
return []
_heapify_max(result)
top = result[0][0]
order = n
if not done:
for elem in it:
if elem < top:
_heapreplace_max(result, (elem, order))
top, _order = result[0]
order += 1
else:
it.destroy()
result.sort()
return [elem for elem, order in result]
else:
# General case, slowest method
it = iter(iterable)
result = List(n)
done = False
for i in range(n):
if it.done():
done = True
break
elem = it.next()
result.append((key(elem), i, elem))
if not result:
it.destroy()
return []
_heapify_max(result)
top = result[0][0]
order = n
if not done:
for elem in it:
k = key(elem)
if k < top:
_heapreplace_max(result, (k, order, elem))
top, _order, _elem = result[0]
order += 1
else:
it.destroy()
result.sort()
return [elem for k, order, elem in result]
def nlargest(n: int, iterable: Generator[T], key=Optional[int](), T: type) -> List[T]:
"""Find the n largest elements in a dataset.
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
"""
if n == 1:
v = List(1)
for a in iterable:
if not v:
v.append(a)
else:
if not isinstance(key, Optional):
if key(a) > key(v[0]):
v[0] = a
elif a > v[0]:
v[0] = a
return v
# When key is none, use simpler decoration
if isinstance(key, Optional):
it = iter(iterable)
result = List(n)
done = False
for i in range(0, -n, -1):
if it.done():
done = True
break
result.append((it.next(), i))
if not result:
it.destroy()
return []
heapify(result)
top = result[0][0]
order = -n
if not done:
for elem in it:
if top < elem:
heapreplace(result, (elem, order))
top, _order = result[0]
order -= 1
else:
it.destroy()
result.sort()
return [elem for elem, order in reversed(result)]
else:
# General case, slowest method
it = iter(iterable)
result = List(n)
done = False
for i in range(0, -n, -1):
if it.done():
done = True
break
elem = it.next()
result.append((key(elem), i, elem))
if not result:
return []
heapify(result)
top = result[0][0]
order = -n
if not done:
for elem in it:
k = key(elem)
if top < k:
heapreplace(result, (k, order, elem))
top, _order, _elem = result[0]
order -= 1
else:
it.destroy()
result.sort()
return [elem for k, order, elem in reversed(result)]
@tuple
class _MergeItem:
value: T
order: int
gen: Generator[T]
key: S
T: type
S: type
def __lt__(self, other):
if isinstance(self.key, Optional):
return (self.value, self.order) < (other.value, other.order)
else:
return (self.key(self.value), self.order, self.value) < (
other.key(other.value),
other.order,
other.value,
)
def merge(*iterables, key=Optional[int](), reverse: bool = False):
items = []
# TODO: unify types of different compatible functions
# TODO: lambdas with void?
def _heapify(x):
if reverse:
_heapify_max(x)
else:
heapify(x)
_heappop = lambda x: _heappop_max(x) if reverse else heappop(x)
_heapreplace = lambda x, s: _heapreplace_max(x, s) if reverse else heapreplace(x, s)
direction = -1 if reverse else 1
order = 0
for it in iterables:
gen = iter(it)
if not gen.done():
items.append(_MergeItem(gen.next(), order * direction, gen, key))
order += 1
_heapify(items)
while len(items) > 1:
while True:
# TODO: @tuple unpacking does not work
value, order, gen = items[0].value, items[0].order, items[0].gen
yield value
if gen.done():
_heappop(items)
break
_heapreplace(items, _MergeItem(gen.next(), order, gen, key))
if items:
# fast case when only a single iterator remains
value, order, gen = items[0].value, items[0].order, items[0].gen
yield value
yield from gen