Welcome, guest | Sign In | My Account | Store | Cart

A simple example of a heap data structure as a C extension. This data structure can store and sort any python object that has a comparison function (i.e. strings, numbers, etc.).

Python, 300 lines
  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
#include "Python.h"
#include "structmember.h"

/*   This is an example type extension.  This is based loosely on a data
 * structure described in 'Mastering Algorithms with C'.  It allocates memory
 * for the underlying array in "rows" instead of on an element-by-element
 * basis.  This does make it faster than the element-by-element allocating
 * version, but the difference is hard to measure until you get up into the
 * millions of elements.
 *
 *   This heap can be used with any Python object that implements a __cmp__
 * function.  I used the Python memory management functions and tried to make
 * this object blend in as much as possible to the Python framework.
 *
 *   Right now the only way to figure out how many items are on the hash is to
 * get the 'size' member of the hash (or keep count).
 */

/*----------------------------------------------------------------------------*
 *                               Heap structure                               *
 *----------------------------------------------------------------------------*/
typedef struct {
  PyObject_HEAD
  int size;        /* number of pointer elements held */
  int minsize;     /* minimum number of allocated elements in cache */
  int allocsize;   /* currently allocated size of cache */
  PyObject **tree; /* the cache */
} Heap;

/*----------------------------------------------------------------------------*
 *                                 Heap push                                  *
 *----------------------------------------------------------------------------*/
static PyObject *
Heap_push(PyObject *self, PyObject *arg)
{
  Heap *heap = (Heap *)self;
  PyObject **new_tree; /* new heap if needed */
  PyObject  *temp;     /* swap placeholder   */
  int cpos;            /* current position   */
  int ppos;            /* parent position    */
  int newsize;         /* size placeholder   */

  /* check to see if there is enough space allocated for the object */
  if (heap->size + 1 > heap->allocsize)
  {
    /* the size of the next row is always one plus the total size */
    newsize = 2*heap->allocsize + 1;

    /* allocate storage for the new node */
    new_tree = (PyObject **)PyMem_Realloc(heap->tree, newsize * sizeof(PyObject *));
    if (new_tree == NULL)
    {
      PyErr_SetString(PyExc_MemoryError, "unable to increase heap storage");
      return NULL;
    }
    else
      /* connect your new data structure and record the allocated size */
      heap->allocsize = newsize;
      heap->tree = new_tree;
  }

  /* insert the node after the last node */
  Py_INCREF(arg);
  heap->tree[heap->size] = arg;

  /* heapify the tree by pushing the contents of the new node upwards */
  cpos = heap->size;
  ppos = (cpos - 1)/2;

  while (cpos > 0 && PyObject_Compare(heap->tree[ppos], heap->tree[cpos]) < 0)
  {
    temp = heap->tree[ppos];
    heap->tree[ppos] = heap->tree[cpos];
    heap->tree[cpos] = temp;

    /* move up one layer in the tree and continue heapifying */
    cpos = ppos;
    ppos = (cpos - 1)/2;
  }

  /* adjust the size of the heap to account for the inserted data */
  heap->size++;
  Py_INCREF(Py_None);
  return Py_None;
}

/*----------------------------------------------------------------------------*
 *                                  Heap pop                                  *
 *----------------------------------------------------------------------------*/
static PyObject *
Heap_pop(PyObject *self)
{
  Heap *heap = (Heap *)self;
  PyObject **new_tree; /* new heap if needed */
  PyObject *data;      /* the top node       */
  PyObject *temp;      /* swap placeholder   */
  int ipos;            /* initial position   */
  int lpos;            /* left position      */
  int rpos;            /* right position     */
  int mpos;            /* modified position  */
  int newsize;         /* size placeholder   */

  /* do not allow extraction from an empty heap */
  if (heap->size == 0)
  {
    PyErr_SetString(PyExc_IndexError, "attempt to pop from empty heap");
    return NULL;
  }

  /* extract the first node, move the last node to the top of the heap */
  data = heap->tree[0];
  temp = heap->tree[heap->size - 1];
  heap->tree[0] = temp;

  /* check to see if you need to make the heap storage smaller */
  newsize = (heap->allocsize - 1)/2;
  if ((heap->size - 1 <= newsize) && (newsize >= heap->minsize))
  {
    new_tree = (PyObject **)PyMem_Realloc(heap->tree, newsize*sizeof(PyObject *));
    if (new_tree == NULL)
    {
      PyErr_SetString(PyExc_MemoryError, "unable to decrease heap storage");
      return NULL;
    }
    else
    {
      /* connect your new data structure and record the allocated size */
      heap->allocsize = newsize;
      heap->tree = new_tree;
    }
  }

  /* since you have pointers to the top and bottom nodes, decrease size */
  heap->size--;
  /* heapify the storage object by pushing the top node down */
  ipos = 0;

  while (1)
  {
    /* select the child to swap with the current node */
    lpos = ipos*2 + 1;
    rpos = ipos*2 + 2;

    if (lpos < heap->size && PyObject_Compare(heap->tree[lpos], heap->tree[ipos]) > 0)
      mpos = lpos;
    else
      mpos = ipos;

    if (rpos < heap->size && PyObject_Compare(heap->tree[rpos], heap->tree[mpos]) > 0)
      mpos = rpos;

    /* when mpos is ipos, the heap property has been restored */
    if (mpos == ipos)
      break;
    else
    {
      /* swap the contents of the current node and the selected child */
      temp = heap->tree[mpos];
      heap->tree[mpos] = heap->tree[ipos];
      heap->tree[ipos] = temp;
    }

    /* move down one level and continue heapifying */
    ipos = mpos;
  }

  return data;
}

/*----------------------------------------------------------------------------*
 *                              Heap destructor                               *
 *----------------------------------------------------------------------------*/
static void
Heap_dealloc(PyObject *self)
{
  int i;
  Heap *heap = (Heap *)self;

  /* remove references to everything on the heap */
  for ( i = 0; i < heap->size; i++ )
    Py_DECREF(heap->tree[i]);

  /* free the memory used by the pointers on the heap, if it exists */
  if (heap->tree != NULL)
    PyMem_Free(heap->tree);

  /* now free the type object */
  self->ob_type->tp_free(self);
}

/*----------------------------------------------------------------------------*
 *                              Heap constructor                              *
 *----------------------------------------------------------------------------*/
static PyObject *
Heap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
  Heap *self;
  PyObject **tree;

  /* initialize an empty heap */
  self = (Heap *)type->tp_alloc(type, 0);
  self->size = 0;      /* number of currently held objects */
  self->minsize = 256; /* minimum number of allocated objects */
  tree = (PyObject **)PyMem_Malloc(self->minsize*sizeof(PyObject *));
  if (tree == NULL)
  {
    /* this is pretty much fatal - return an error and exit */
    PyErr_SetString(PyExc_MemoryError, "unable to allocate heap storage");
    self->allocsize = 0;
    return NULL;
  }
  else
  {
    /* return a new Heap */
    self->tree = tree;
    self->allocsize = self->minsize; 
    return (PyObject *)self;
  }
}

/*----------------------------------------------------------------------------*
 *                                Heap members                                *
 *----------------------------------------------------------------------------*/
static PyMemberDef Heap_members[] = {
  {"size", T_INT, offsetof(Heap, size), 0, "number of objects in the heap"},
  {NULL}  /* sentinel */
};

static PyMethodDef Heap_methods[] = {
  {"push", (PyCFunction)Heap_push, METH_O,      "push an object onto the heap"},
  {"pop",  (PyCFunction)Heap_pop,  METH_NOARGS, "pop the top object from the heap"},
  {NULL}  /* sentinel */
};

static PyTypeObject HeapType = {
  PyObject_HEAD_INIT(NULL)
  0,                         /* ob_size */
  "Heap",                    /* tp_name */
  sizeof(Heap),              /* tp_basicsize */
  0,                         /* tp_itemsize */
  (destructor)Heap_dealloc,  /* tp_dealloc */
  0,                         /* tp_print */
  0,                         /* tp_getattr */
  0,                         /* tp_setattr */
  0,                         /* tp_compare */
  0,                         /* tp_repr */
  0,                         /* tp_as_number */
  0,                         /* tp_as_sequence */
  0,                         /* tp_as_mapping */
  0,                         /* tp_hash  */
  0,                         /* tp_call */
  0,                         /* tp_str */
  0,                         /* tp_getattro*/
  0,                         /* tp_setattro*/
  0,                         /* tp_as_buffer*/
  Py_TPFLAGS_DEFAULT,        /* tp_flags*/
  "Heap objects",            /* tp_doc */
  0,                         /* tp_traverse */
  0,                         /* tp_clear */
  0,                         /* tp_richcompare */
  0,                         /* tp_weaklistoffset */
  0,                         /* tp_iter */
  0,                         /* tp_iternext */
  Heap_methods,              /* tp_methods */
  Heap_members,              /* tp_members */
  0,                         /* tp_getset */
  0,                         /* tp_base */
  0,                         /* tp_dict */
  0,                         /* tp_descr_get */
  0,                         /* tp_descr_set */
  0,                         /* tp_dictoffset */
  0,                         /* tp_init */
  0,                         /* tp_alloc */
  Heap_new,                  /* tp_new */
};

static PyMethodDef module_methods[] = {
  {NULL}  /* sentinel */
};

/* declarations for DLL export */
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initheap(void) 
{
  PyObject* m;

  if (PyType_Ready(&HeapType) < 0)
    return;

  m = Py_InitModule3("heap", module_methods, "Example module that implements a heap");

  if (m == NULL)
    return;

  Py_INCREF(&HeapType);
  PyModule_AddObject(m, "Heap", (PyObject *)&HeapType);
}

Heaps (Priority Queues) are used in many algorithms (minimum spanning trees, etc). I was interested in writing extension modules and was looking for something simple to try out. Most of what I learned was from the Python C API, the Extending and Embedding tutorial, and this website. I have tried this code out on Linux and Windows 2000 by using the distutils module (an example setup.py file follows):

from distutils.core import Extension, setup setup (name="heap", version="1.0", maintainer="Tim Meehan", description="simple Python extention type", ext_modules=[Extension("heap", ["heap.c",])] )

Here is an example of the Heap in action on my windows machine (it works on more than just numbers, I just used numbers as an example): ActivePython 2.2.2 Build 224 (ActiveState Corp.) based on Python 2.2.2 (#37, Nov 26 2002, 10:24:37) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information.

>>> from heap import Heap
>>> from random import random
>>> a = Heap()
>>> a.pop()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: attempt to pop from empty heap
>>> for i in range(10):
...   a.push(random())
...
>>> for i in range(10):
...   a.pop()
...
0.89993181004742606
0.82018958943326037
0.63165609014853752
0.52421761109388232
0.43681731273589941
0.3583793139350786
0.20696096641639428
0.11730573937621958
0.097850757250128151
0.066719074253705379
>>>
Created by Tim Meehan on Thu, 4 Dec 2003 (PSF)
Python recipes (4591)
Tim Meehan's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks