Mastering Python Second Edition Release Code

This commit is contained in:
Rick van Hattem
2022-05-05 18:25:55 +02:00
commit 3223a43fe3
454 changed files with 20230 additions and 0 deletions
@@ -0,0 +1,23 @@
import pathlib
import setuptools
# Get the current directory
PROJECT_PATH = pathlib.Path(__file__).parent
sum_of_squares = setuptools.Extension('sum_of_squares', sources=[
# Get the relative path to sum_of_squares.c
str(PROJECT_PATH / 'sum_of_squares.c'),
])
if __name__ == '__main__':
setuptools.setup(
name='T_04_C_extensions',
version='0.1.0',
packages=setuptools.find_packages(),
url='https://wol.ph/',
author='Rick van Hattem',
author_email='wolph@wol.ph',
ext_modules=[sum_of_squares],
)
@@ -0,0 +1,49 @@
#include <Python.h>
static PyObject* sum_of_squares(PyObject *self, PyObject
*args){
/* Declare the variables */
int n;
int total = 0;
/* Parse the arguments */
if(!PyArg_ParseTuple(args, "i", &n)){
return NULL;
}
/* The actual summing code */
for(int i=0; i<n; i++){
if((i * i) < n){
total += i * i;
}else{
break;
}
}
/* Return the number but convert it to a Python object first
*/
return PyLong_FromLong(total);
}
static PyMethodDef methods[] = {
/* Register the function */
{"sum_of_squares", sum_of_squares, METH_VARARGS,
"Sum the perfect squares below n"},
/* Indicate the end of the list */
{NULL, NULL, 0, NULL},
};
static struct PyModuleDef module = {
PyModuleDef_HEAD_INIT,
"sum_of_squares", /* Module name */
NULL, /* Module documentation */
-1, /* Module state, -1 means global. This parameter is
for sub-interpreters */
methods,
};
/* Initialize the module */
PyMODINIT_FUNC PyInit_sum_of_squares(void){
return PyModule_Create(&module);
}