#Reachability #Single Gold Star #Define a procedure, reachable(graph, node), that takes as input a graph and a #starting node, and returns a list of all the nodes in the graph that can be #reached by following zero or more edges starting from node. The input graph is #represented as a Dictionary where each node in the graph is a key in the #Dictionary, and the value associated with a key is a list of the nodes that the #key node is connected to. The nodes in the returned list may appear in any #order, but should not contain any duplicates. def reachable(graph, node): search_list = [node] nodes = [node] while search_list: for each in graph[search_list[0]]: if each not in nodes: nodes.append(each) search_list.append(each) search_list.pop(0) return nodes #For example, graph = {'a': ['b', 'c'], 'b': ['a', 'c'], 'c': ['b', 'd'], 'd': ['a'], 'e': ['a']} print reachable(graph, 'a') #>>> ['a', 'c', 'd', 'b'] print reachable(graph, 'd') #>>> ['d', 'a', 'c', 'b'] print reachable(graph, 'e') #>>> ['e', 'a', 'c', 'd', 'b']
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question