Note

This is the documentation for the current state of the development branch of rustworkx. The documentation or APIs here can change prior to being released.

rustworkx.ancestors#

ancestors(graph, node, /)#

Retrieve all ancestors of a specified node in a directed graph.

This function differs from the PyDiGraph.predecessors() method, which only returns nodes that have a direct edge leading to the specified node. In contrast, this function returns all nodes that have a path leading to the specified node, regardless of the number of edges in between.

>>> G = rx.PyDiGraph()
>>> G.add_nodes_from(range(5))
NodeIndices[0, 1, 2, 3, 4]
>>> G.add_edges_from_no_data([(0, 2), (1, 2), (2, 3), (3, 4)])
[0, 1, 2, 3]
>>> rx.ancestors(G, 3)
{0, 1, 2}

See also

See also predecessors().

Parameters:
  • graph (PyDiGraph) – The directed graph from which to retrieve ancestors.

  • node (int) – The index of the node for which to find ancestors.

Returns:

A set containing the indices of all ancestor nodes of the specified node.

Return type:

set[int]

Raises:

IndexError – If the specified node is not present in the directed graph.