Search code examples
pythonnetworkxmoodle

Networkx dfs_edges not functioning as intended by professor


The expected output from dfs_edges(G, 4) is correct, but it's off by the position of one edges and I can't figure out why

Input:

G = nx.Graph()
edges = [(1,2),(1,3),(1,5),(2,5),(2,6),(3,4),(3,5),(4,5),(4,6),(4,7),(5,6)]
root = 4
G.add_edges_from(edges)
printGraph(G)

Expected Output:

DFS traversal from from 4 = [(4, 3), (4, 7), (3, 1), (1, 2), (2, 5), (5, 6)]

My Code:

import networkx as nx
def printGraph(G):
    print("DFS traversal from from 4 =", list(nx.dfs_edges(G,4)))

Result from code:

DFS traversal from from 4 = [(4, 3), (3, 1), (1, 2), (2, 5), (5, 6), (4, 7)]

The problem is the position of the (4, 7) edge, while I can manually place it where it should be, but that would mean it wouldn't work on the hidden text cases (Moodle)


Solution

  • The answer got and expected are both correct, turns out he didn't want dfs_edges, he wanted the edges of the dfs tree instead, so this worked:

    print("DFS traversal from from 4 =", nx.dfs_tree(G, root)).edges())