HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Finding the closest node

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
nodetheclosestfinding

Problem

I have a function that I need to optimize:

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)
    for i in nodes:
        if depth+1 > maxdepth:
            return False
        if search(graph, i, maxdepth, depth+1):
            return i
   return False


graph should be a networkx graph object. How can I optimize this? This should find the closest node in the network with 'station' attribute to True.

Solution

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)


Why store the neighbor in the list? Instead of putting it in a list, just combine your two loops.

for i in nodes:


i typically stands for index. I suggest using neighbor to make your code easier to follow

if depth+1 > maxdepth:
        return False


This doesn't relate to this individual node. What is it doing inside this loop?

if search(graph, i, maxdepth, depth+1):
            return i
   return False


Failure to find is better reported using None rather than False.

Code Snippets

def search(graph, node, maxdepth = 10, depth = 0):
    nodes = []
    for neighbor in graph.neighbors_iter(node):
        if graph.node[neighbor].get('station', False):
            return neighbor
        nodes.append(neighbor)
for i in nodes:
if depth+1 > maxdepth:
        return False
if search(graph, i, maxdepth, depth+1):
            return i
   return False

Context

StackExchange Code Review Q#24546, answer score: 4

Revisions (0)

No revisions yet.