Python Loadable Extension in C
The Towers of Hanoi as a Python Loadable Extension in C.
/*
* Copyright (C) 2002 Amit Singh. All Rights Reserved.
* http://hanoi.kernelthread.com
*
* hanoi-pymod.c: The Towers Of Hanoi as a loadable Python extension.
*
* In order to compile, do the following (replace /usr/include/python2.2
* with the appropriate include path for your Python installation):
*
* gcc -Wall -fPIC -I/usr/include/python2.2 -shared -o hanoi.so hanoi-pymod.c
*
* Thereafter you can test this module as follows:
*
* -- cut here --
#! /usr/bin/python
#
import hanoi
# solve for 3 disks
moves = hanoi.solve(3)
print moves
* -- cut here --
*/
#include <Python.h>
#include <pyerrors.h>
#define MAXDISKS 10
#define DISK_FROM 1
#define DISK_USING 2
#define DISK_TO 3
static PyObject *hanoi(PyObject *, PyObject *);
static PyObject *dohanoi(int, int, int, int, PyObject *);
static PyMethodDef HanoiMethods[] = {
{ "solve", hanoi, METH_VARARGS },
{ NULL, NULL } /* sentinel */
};
static PyObject *
dohanoi(int n, int f, int u, int t, PyObject *M)
{
if (n == 1) {
return (PyObject *)PyList_Append(M, Py_BuildValue("[i,i]", f, t));
} else {
dohanoi(n - 1, f, t, u, M);
PyList_Append(M, Py_BuildValue("[i,i]", f, t));
dohanoi(n - 1, u, f, t, M);
}
/* to shut up -Wall */
return M;
}
static PyObject *
hanoi(PyObject *self, PyObject *args)
{
int ndisks = 0;
if (!PyArg_ParseTuple(args, "i", &ndisks)) {
return NULL;
}
if ((ndisks <= 0) || (ndisks > MAXDISKS)) {
PyErr_SetString(PyExc_OverflowError, "number of disks too large");
return NULL;
}
return dohanoi(ndisks, DISK_FROM, DISK_USING, DISK_TO, PyList_New(0));
}
void
init_hanoi()
{
(void)Py_InitModule("hanoi", HanoiMethods);
}
void
inithanoi()
{
(void)Py_InitModule("hanoi", HanoiMethods);
}
/* FINIS */