Your code has many issues here. First of all, if no path exists between a Node(A) and a Node(B), the function returns None.
And since on the next recusrion, you try to add [source] + path_to_friend(network, new_source, destination)
which basically is equivalent to [source] + None
it will simply fail and raise the error you just had. To solve this, we will simply test the result of path_to_friend before we append it to the result
def path_to_friend(network, source, destination):
if source == destination:
return [destination]
else:
for new_source in network[source][0]:
#print 'source> '+ source + '; new source> ' + new_source
sub_path = path_to_friend(network, new_source, destination)
if sub_path is not None:
return [source] + sub_path
The second problem you will probably encounter, is in the case there are cycles in the network. In which case, you might find yourself in an infinite loop:
Node A visits Node B which in turn visits Node A....
To fix that, we will use a set that keeps track of the visited nodes and pass it along the function
def path_to_friend(network, source, destination, visited=None):
if source == destination:
return [destination]
else:
visited = visited or set()
for new_source in network[source][0]:
if new_source not in visited: # check if the next node was already visited
visited.add(new_source) # add the next node to the list of visited nodes
#print 'source> '+ source + '; new source> ' + new_source
sub_path = path_to_friend(network, new_source, destination, visited)
if sub_path is not None:
return [source] + sub_path