""" Authors: Peter Mawhorter, Indira Ruslanova Consulted: Date: 2022-3-3 Purpose: Example file for writing code to find distances to unexplored nodes. """ # Import the library (note: it must be installed for this to work) import networkx as nx #---------------# # Graph metrics # #---------------# def findUnknownDistances(graph, startName): """ Given a graph and the name of a starting node, finds the distance from that starting node to each node whose name starts with 'unknown:' and returns a list of those distances. Distances are measured in terms of number of hops in the graph, which is just an integer. """ # TODO: write this function :) distList = [] unknownList = [] #go through every node for node in graph: #check if it starts with "unknown" if node.startswith("unknown"): unknownNode = node #add to the unknownList if node starts with "unknown" unknownList.append(unknownNode) #for every unknown node in the list for unknown in unknownList: try: #calculate the path listNodes = nx.shortest_path(G=graph, source=startName, target=unknown, weight=None, method="dijkstra") #except for when there is no path except: nx.exception.NetworkXNoPath continue #counter to keep track of how many nodes there are countNodes = 0 #not counting the start node and the target node themselves listNodes.remove(startName) listNodes.remove(unknown) #count how many nodes there are for node in listNodes: countNodes+=1 #add to list of distances between nodes distList.append(countNodes) return (distList) #---------# # Testing # #---------# # I put your code from last week into `exampleGraph.py` and the variable # `example` contains the graph you built, plus a few nodes whose names # start with 'unknown:'. from exampleGraph import example # noqa print("Distances to unknown points from node A:") print(findUnknownDistances(example, 'A')) print("Distances to unknown points from node C:") print(findUnknownDistances(example, 'C')) print("Distances to unknown points from node E:") print(findUnknownDistances(example, 'E'))