uidipythontool /DICK.B1/IronPython.Modules/_heapq.cs

Language C# Lines 301
MD5 Hash a72d586c7c3f708d857425e57c5d4914 Estimated Cost $5,906 (why?)
Repository https://bitbucket.org/williamybs/uidipythontool.git View Raw File View Project SPDX
  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
/* ****************************************************************************
 *
 * Copyright (c) Microsoft Corporation. 
 *
 * This source code is subject to terms and conditions of the Microsoft Public License. A 
 * copy of the license can be found in the License.html file at the root of this distribution. If 
 * you cannot locate the  Microsoft Public License, please send an email to 
 * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound 
 * by the terms of the Microsoft Public License.
 *
 * You must not remove this notice, or any other, from this software.
 *
 *
 * ***************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime;
using IronPython.Runtime.Binding;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;

[assembly: PythonModule("_heapq", typeof(IronPython.Modules.PythonHeapq))]
namespace IronPython.Modules {
    public static class PythonHeapq {
        public const string __doc__ = "implements a heapq or priority queue.";
        public const string __about__ = "Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k.";

        #region public API

        [Documentation("Transform list into a heap, in-place, in O(len(heap)) time.")]
        public static void heapify(CodeContext/*!*/ context, List list) {
            lock (list) {
                DoHeapify(context, list);
            }
        }

        [Documentation("Pop the smallest item off the heap, maintaining the heap invariant.")]
        public static object heappop(CodeContext/*!*/ context, List list) {
            lock (list) {
                int last = list._size - 1;
                if (last < 0) {
                    throw PythonOps.IndexError("index out of range");
                }
                list.FastSwap(0, last);
                list._size--;
                SiftDown(context, list, 0, last - 1);
                return list._data[list._size];
            }
        }

        [Documentation("Push item onto heap, maintaining the heap invariant.")]
        public static void heappush(CodeContext/*!*/ context, List list, object item) {
            lock (list) {
                list.AddNoLock(item);
                SiftUp(context, list, list._size - 1);
            }
        }

        [Documentation("Push item on the heap, then pop and return the smallest item\n"
            + "from the heap. The combined action runs more efficiently than\n"
            + "heappush() followed by a separate call to heappop()."
            )]
        public static object heappushpop(CodeContext/*!*/ context, List list, object item) {
            lock (list) {
                return DoPushPop(context, list, item);
            }
        }

        [Documentation("Pop and return the current smallest value, and add the new item.\n\n"
            + "This is more efficient than heappop() followed by heappush(), and can be\n"
            + "more appropriate when using a fixed-size heap. Note that the value\n"
            + "returned may be larger than item!  That constrains reasonable uses of\n"
            + "this routine unless written as part of a conditional replacement:\n\n"
            + "        if item > heap[0]:\n"
            + "            item = heapreplace(heap, item)\n"
            )]
        public static object heapreplace(CodeContext/*!*/ context, List list, object item) {
            lock (list) {
                object ret = list._data[0];
                list._data[0] = item;
                SiftDown(context, list, 0, list._size - 1);
                return ret;
            }
        }

        [Documentation("Find the n largest elements in a dataset.\n\n"
            + "Equivalent to:  sorted(iterable, reverse=True)[:n]\n"
            )]
        public static List nlargest(CodeContext/*!*/ context, int n, object iterable) {
            if (n <= 0) {
                return new List();
            }

            List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge
            IEnumerator en = PythonOps.GetEnumerator(iterable);

            // populate list with first n items
            for (int i = 0; i < n; i++) {
                if (!en.MoveNext()) {
                    // fewer than n items; finish up here
                    HeapSort(context, ret, true);
                    return ret;
                }
                ret.append(en.Current);
            }

            // go through the remainder of the iterator, maintaining a min-heap of the n largest values
            DoHeapify(context, ret);
            while (en.MoveNext()) {
                DoPushPop(context, ret, en.Current);
            }

            // return the largest items, in descending order
            HeapSort(context, ret, true);
            return ret;
        }

        [Documentation("Find the n smallest elements in a dataset.\n\n"
            + "Equivalent to:  sorted(iterable)[:n]\n"
            )]
        public static List nsmallest(CodeContext/*!*/ context, int n, object iterable) {
            if (n <= 0) {
                return new List();
            }

            List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge
            IEnumerator en = PythonOps.GetEnumerator(iterable);

            // populate list with first n items
            for (int i = 0; i < n; i++) {
                if (!en.MoveNext()) {
                    // fewer than n items; finish up here
                    HeapSort(context, ret);
                    return ret;
                }
                ret.append(en.Current);
            }

            // go through the remainder of the iterator, maintaining a max-heap of the n smallest values
            DoHeapifyMax(context, ret);
            while (en.MoveNext()) {
                DoPushPopMax(context, ret, en.Current);
            }

            // return the smallest items, in ascending order
            HeapSort(context, ret);
            return ret;
        }

        #endregion

        #region private implementation details (NOTE: thread-unsafe)

        private static bool IsLessThan(CodeContext/*!*/ context, object x, object y) {
            object ret;
            if (PythonTypeOps.TryInvokeBinaryOperator(context, x, y, "__lt__", out ret) &&
                !Object.ReferenceEquals(ret, NotImplementedType.Value)) {
                return Converter.ConvertToBoolean(ret);
            } else if (PythonTypeOps.TryInvokeBinaryOperator(context, y, x, "__le__", out ret) &&
                !Object.ReferenceEquals(ret, NotImplementedType.Value)) {
                return !Converter.ConvertToBoolean(ret);
            } else {
                return PythonContext.GetContext(context).LessThan(x, y);
            }
        }

        private static void HeapSort(CodeContext/*!*/ context, List list) {
            HeapSort(context, list, false);
        }

        private static void HeapSort(CodeContext/*!*/ context, List list, bool reverse) {
            // for an ascending sort (reverse = false), use a max-heap, and vice-versa
            if (reverse) {
                DoHeapify(context, list);
            } else {
                DoHeapifyMax(context, list);
            }

            int last = list._size - 1;
            while (last > 0) {
                // put the root node (max if ascending, min if descending) at the end
                list.FastSwap(0, last);
                // shrink heap by 1
                last--;
                // maintain heap invariant
                if (reverse) {
                    SiftDown(context, list, 0, last);
                } else {
                    SiftDownMax(context, list, 0, last);
                }
            }
        }

        private static void DoHeapify(CodeContext/*!*/ context, List list) {
            int last = list._size - 1;
            int start = (last - 1) / 2; // index of last parent node
            // Sift down each parent node from right to left.
            while (start >= 0) {
                SiftDown(context, list, start, last);
                start--;
            }
        }

        private static void DoHeapifyMax(CodeContext/*!*/ context, List list) {
            int last = list._size - 1;
            int start = (last - 1) / 2; // index of last parent node
            // Sift down each parent node from right to left.
            while (start >= 0) {
                SiftDownMax(context, list, start, last);
                start--;
            }
        }

        private static object DoPushPop(CodeContext/*!*/ context, List heap, object item) {
            object first;
            if (heap._size == 0 || !IsLessThan(context, first = heap._data[0], item)) {
                return item;
            }
            heap._data[0] = item;
            SiftDown(context, heap, 0, heap._size - 1);
            return first;
        }

        private static object DoPushPopMax(CodeContext/*!*/ context, List heap, object item) {
            object first;
            if (heap._size == 0 || !IsLessThan(context, item, first = heap._data[0])) {
                return item;
            }
            heap._data[0] = item;
            SiftDownMax(context, heap, 0, heap._size - 1);
            return first;
        }

        private static void SiftDown(CodeContext/*!*/ context, List heap, int start, int stop) {
            int parent = start;
            int child;
            while ((child = parent * 2 + 1) <= stop) {
                // find the smaller sibling
                if (child + 1 <= stop && IsLessThan(context, heap._data[child + 1], heap._data[child])) {
                    child++;
                }
                // check if min-heap property is violated
                if (IsLessThan(context, heap._data[child], heap._data[parent])) {
                    heap.FastSwap(parent, child);
                    parent = child;
                } else {
                    return;
                }
            }
        }

        private static void SiftDownMax(CodeContext/*!*/ context, List heap, int start, int stop) {
            int parent = start;
            int child;
            while ((child = parent * 2 + 1) <= stop) {
                // find the larger sibling
                if (child + 1 <= stop && IsLessThan(context, heap._data[child], heap._data[child + 1])) {
                    child++;
                }
                // check if max-heap property is violated
                if (IsLessThan(context, heap._data[parent], heap._data[child])) {
                    heap.FastSwap(parent, child);
                    parent = child;
                } else {
                    return;
                }
            }
        }

        private static void SiftUp(CodeContext/*!*/ context, List heap, int index) {
            while (index > 0) {
                int parent = (index - 1) / 2;
                if (IsLessThan(context, heap._data[index], heap._data[parent])) {
                    heap.FastSwap(parent, index);
                    index = parent;
                } else {
                    return;
                }
            }
        }

        private static void SiftUpMax(CodeContext/*!*/ context, List heap, int index) {
            while (index > 0) {
                int parent = (index - 1) / 2;
                if (IsLessThan(context, heap._data[parent], heap._data[index])) {
                    heap.FastSwap(parent, index);
                    index = parent;
                } else {
                    return;
                }
            }
        }

        #endregion
    }
}
Back to Top