| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
#if !defined(Py_LIMITED_API) |
| 9 |
#define Py_LIMITED_API 3 |
| 10 |
#endif |
| 11 |
#define PY_SSIZE_T_CLEAN |
| 12 |
#include <Python.h> |
| 13 |
|
| 14 |
|
| 15 |
#define MODULE_NAME calculate |
| 16 |
#define MODULE_DOCS "Calculates Fibonacci numbers." |
| 17 |
|
| 18 |
|
| 19 |
#define _STRINGIFY(x) #x |
| 20 |
#define STRINGIFY(x) _STRINGIFY(x) |
| 21 |
|
| 22 |
|
| 23 |
static PyObject *fib(PyObject *self, PyObject *args) |
| 24 |
{ |
| 25 |
long int index; |
| 26 |
if (!PyArg_ParseTuple(args, "l", &index)) { |
| 27 |
PyErr_SetString(PyExc_ValueError, "An index must be specified."); |
| 28 |
} |
| 29 |
|
| 30 |
long int current_value = 1; |
| 31 |
long int previous_value = 0; |
| 32 |
index--; |
| 33 |
for ( ; index > 0 ; --index) { |
| 34 |
long int next_value = current_value + previous_value; |
| 35 |
previous_value = current_value; |
| 36 |
current_value = next_value; |
| 37 |
} |
| 38 |
return PyLong_FromLong(current_value); |
| 39 |
} |
| 40 |
|
| 41 |
|
| 42 |
static PyMethodDef methods[] = |
| 43 |
{ |
| 44 |
{ |
| 45 |
"fib", |
| 46 |
fib, |
| 47 |
METH_VARARGS, |
| 48 |
PyDoc_STR("Calculate a Fibonacci number.\n" |
| 49 |
"\n" |
| 50 |
":param index: Index of the number in the Fibonacci sequence\n" |
| 51 |
" to calculate.\n" |
| 52 |
"\n" |
| 53 |
":returns: Fibonacci number at the specified index.\n" |
| 54 |
" For example an index of 7 will return 13\n"), |
| 55 |
}, |
| 56 |
}; |
| 57 |
|
| 58 |
#if PY_MAJOR_VERSION >= 3 |
| 59 |
|
| 60 |
static struct PyModuleDef module = |
| 61 |
{ |
| 62 |
PyModuleDef_HEAD_INIT, |
| 63 |
STRINGIFY(MODULE_NAME), |
| 64 |
PyDoc_STR(MODULE_DOCS), |
| 65 |
-1, |
| 66 |
methods, |
| 67 |
}; |
| 68 |
#endif |
| 69 |
|
| 70 |
|
| 71 |
#define _PYINIT_FUNCTION_NAME(prefix, name) prefix ## name |
| 72 |
#define PYINIT_FUNCTION_NAME(prefix, name) _PYINIT_FUNCTION_NAME(prefix, name) |
| 73 |
|
| 74 |
|
| 75 |
#if PY_MAJOR_VERSION >= 3 |
| 76 |
PyMODINIT_FUNC |
| 77 |
PYINIT_FUNCTION_NAME(PyInit_, MODULE_NAME)(void) |
| 78 |
{ |
| 79 |
return PyModule_Create(&module); |
| 80 |
} |
| 81 |
#else |
| 82 |
PyMODINIT_FUNC |
| 83 |
PYINIT_FUNCTION_NAME(init, MODULE_NAME)(void) |
| 84 |
{ |
| 85 |
|
| 86 |
(void)Py_InitModule(STRINGIFY(MODULE_NAME), methods); |
| 87 |
} |
| 88 |
#endif |