Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Added

- Added support for Python 3.15.
- Added `Graph.count_triangles()` to count triangles without listing them (#865).

### Changed

Expand Down
22 changes: 22 additions & 0 deletions src/_igraph/graphobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
9 changes: 9 additions & 0 deletions tests/test_motifs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down