diff --git a/CHANGELOG.md b/CHANGELOG.md index ce2624727..b8ac88c94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Added - Added support for Python 3.15. +- Added `Graph.count_triangles()` to count triangles without listing them (#865). ### Changed diff --git a/src/_igraph/graphobject.c b/src/_igraph/graphobject.c index 478d62508..fd263b813 100644 --- a/src/_igraph/graphobject.c +++ b/src/_igraph/graphobject.c @@ -7495,6 +7495,19 @@ PyObject *igraphmodule_Graph_dyad_census(igraphmodule_GraphObject *self, PyObjec return Py_BuildValue("NNN", mut_o, asym_o, nul_o); } +/** \ingroup python_interface_graph + * \brief Counts the triangles of the graph + * \sa igraph_count_triangles + */ +PyObject *igraphmodule_Graph_count_triangles(igraphmodule_GraphObject *self, PyObject* Py_UNUSED(_null)) { + igraph_real_t count; + + if (igraph_count_triangles(&self->g, &count)) { + return igraphmodule_handle_igraph_error(); + } + return igraphmodule_real_t_to_PyObject(count, IGRAPHMODULE_TYPE_INT); +} + /** \ingroup python_interface_graph * \brief Lists the triangles of the graph * \return the triangles of the graph as a list of triplets with vertex IDs @@ -17052,6 +17065,15 @@ struct PyMethodDef igraphmodule_Graph_methods[] = { "It is advised to use that. The name of the triplet classes are\n" "also documented there.\n\n" }, + {"count_triangles", (PyCFunction) igraphmodule_Graph_count_triangles, + METH_NOARGS, + "count_triangles()\n--\n\n" + "Counts the triangles in the graph.\n\n" + "Edge directions, multiple edges and self-loops are ignored.\n\n" + "@return: the number of fully connected vertex triples.\n" + "@see: L{list_triangles()} to list the triangles, and\n" + " L{transitivity_undirected()} for the global transitivity (clustering coefficient)." + }, {"list_triangles", (PyCFunction) igraphmodule_Graph_list_triangles, METH_NOARGS, "list_triangles()\n--\n\n" diff --git a/tests/test_motifs.py b/tests/test_motifs.py index d0f9131fa..b5395a9cb 100644 --- a/tests/test_motifs.py +++ b/tests/test_motifs.py @@ -35,6 +35,15 @@ def testTriads(self): class TrianglesTests(unittest.TestCase): + def testCountTriangles(self): + self.assertEqual(Graph().count_triangles(), 0) + self.assertEqual(Graph.Full(5).count_triangles(), 10) + + g = Graph([(0, 1), (1, 2), (0, 2), (1, 0), (2, 2)], directed=True) + count = g.count_triangles() + self.assertIsInstance(count, int) + self.assertEqual(count, 1) + def testListTriangles(self): g = Graph.Famous("petersen") self.assertEqual([], g.list_triangles())