MCPcopy Create free account
hub / github.com/bslatkin/effectivepython / dot_product

Function dot_product

example_code/item_096/my_extension/dot_product.c:19–56  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

17#include "my_extension.h"
18
19PyObject *dot_product(PyObject *self, PyObject *args)
20{
21 PyObject *left, *right;
22 if (!PyArg_ParseTuple(args, "OO", &left, &right)) {
23 return NULL;
24 }
25 if (!PyList_Check(left) || !PyList_Check(right)) {
26 PyErr_SetString(PyExc_TypeError, "Both arguments must be lists");
27 return NULL;
28 }
29
30 Py_ssize_t left_length = PyList_Size(left);
31 Py_ssize_t right_length = PyList_Size(right);
32 if (left_length == -1 || right_length == -1) {
33 return NULL;
34 }
35 if (left_length != right_length) {
36 PyErr_SetString(PyExc_ValueError, "Lists must be the same length");
37 return NULL;
38 }
39
40 double result = 0;
41
42 for (Py_ssize_t i = 0; i < left_length; i++) {
43 PyObject *left_item = PyList_GET_ITEM(left, i);
44 PyObject *right_item = PyList_GET_ITEM(right, i);
45
46 double left_double = PyFloat_AsDouble(left_item);
47 double right_double = PyFloat_AsDouble(right_item);
48 if (PyErr_Occurred()) {
49 return NULL;
50 }
51
52 result += left_double * right_double;
53 }
54
55 return PyFloat_FromDouble(result);
56}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected