all_triangles#
- all_triangles(G, nbunch=None)[source]#
Yields all unique triangles in an undirected graph.
A triangle is a set of three distinct nodes where each node is connected to the other two.
- Parameters:
- GNetworkX graph
An undirected graph.
- nbunchnode, iterable of nodes, or None (default=None)
If a node or iterable of nodes, only triangles involving at least one node in
nbunch
are yielded. IfNone
, yields all unique triangles in the graph.
- Yields:
- tuple
A tuple of three nodes forming a triangle
(u, v, w)
.
See also
all_triads()
related function for directed graphs
Notes
This algorithm ensures each triangle is yielded once using an internal node ordering. In multigraphs, triangles are identified by their unique set of nodes, ignoring multiple edges between the same nodes. Self-loops are ignored. Runs in
O(m * d)
time in the worst case, wherem
the number of edges andd
the maximum degree.Examples
>>> G = nx.complete_graph(4) >>> sorted([sorted(t) for t in all_triangles(G)]) [[0, 1, 2], [0, 1, 3], [0, 2, 3], [1, 2, 3]]