Skip to content

Commit

Permalink
DOC: Add example to generic_bfs_edges to demonstrate the neighbors
Browse files Browse the repository at this point in the history
…param (networkx#7072)

* DOC: Add examples to generic_bfs_edges docstring.

Two main changes:
 * Ensure that  is being called in its docstring
   examples, not bfs_edges
 * Add at least one example demonstrating the generic neighbors
   param.

* Simpler odds first example.
  • Loading branch information
rossbar authored and cvanelteren committed Apr 22, 2024
1 parent dde1fb8 commit 7e9fe68
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions networkx/algorithms/traversal/breadth_first_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def generic_bfs_edges(G, source, neighbors=None, depth_limit=None, sort_neighbor
A function that takes a newly visited node of the graph as input
and returns an *iterator* (not just a list) of nodes that are
neighbors of that node with custom ordering. If not specified, this is
just the``G.neighbors`` method, but in general it can be any function
just the ``G.neighbors`` method, but in general it can be any function
that returns an iterator over some or all of the neighbors of a
given node, in any order.
Expand All @@ -63,11 +63,26 @@ def generic_bfs_edges(G, source, neighbors=None, depth_limit=None, sort_neighbor
Examples
--------
>>> G = nx.path_graph(3)
>>> list(nx.bfs_edges(G, 0))
[(0, 1), (1, 2)]
>>> list(nx.bfs_edges(G, source=0, depth_limit=1))
[(0, 1)]
>>> G = nx.path_graph(7)
>>> list(nx.generic_bfs_edges(G, source=0))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> list(nx.generic_bfs_edges(G, source=2))
[(2, 1), (2, 3), (1, 0), (3, 4), (4, 5), (5, 6)]
>>> list(nx.generic_bfs_edges(G, source=2, depth_limit=2))
[(2, 1), (2, 3), (1, 0), (3, 4)]
The `neighbors` param can be used to specify the visitation order of each
node's neighbors generically. In the following example, we modify the default
neighbor to return *odd* nodes first:
>>> def odd_first(n):
... return sorted(G.neighbors(n), key=lambda x: x % 2, reverse=True)
>>> G = nx.star_graph(5)
>>> list(nx.generic_bfs_edges(G, source=0)) # Default neighbor ordering
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
>>> list(nx.generic_bfs_edges(G, source=0, neighbors=odd_first))
[(0, 1), (0, 3), (0, 5), (0, 2), (0, 4)]
Notes
-----
Expand Down

0 comments on commit 7e9fe68

Please sign in to comment.