简体   繁体   中英

Python Shortest path between 2 points

I have found many algorithms and approaches that talk about finding the shortest path between 2 points , but i have this situation where the data is modeled as :

[(A,B),(C,D),(B,C),(D,E)...] # list of possible paths

If we suppose i need the path from A to E , the result should be:

(A,B)=>(B,C)=>(C,D)=>(D,E)

but i can't find a pythonic way to do this search.

The Pythonic way is to to use a module if one exists. As in this case, we know, networkx is there , we can write

Implementation

import networkx as nx
G = nx.Graph([('A','B'),('C','D'),('B','C'),('D','E')])
path = nx.shortest_path(G, 'A', 'E')

Output

zip(path, path[1:])
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E')]

If you think of your points as vertices in a graph, your pairs as edges in that graph, then you can assign to edge graph edge a weight equal to the distance between your points.

Framed this way your problem is just the classic shortest path problem .

You asked for a Pythonic way to write it. The only advice I'd give is represent your graph as a dictionary, so that each key is a point, the returned values are a list of the other points directly reachable from that point. That will make traversing the graph faster. graph[C] -> [B, D] for your example.

Here is a solution using A*:

pip install pyformulas==0.2.8

import pyformulas as pf

transitions = [('A', 'B'), ('B', 'C'), ('C', 'A'), ('C', 'F'), ('D', 'F'), ('F', 'D'), ('F', 'B'), ('D', 'E'), ('E', 'C')]

initial_state = ('A',)

def expansion_fn(state):
    valid_transitions = [tn for tn in transitions if tn[0] == state[-1]]
    step_costs = [1 for t in valid_transitions]

    return valid_transitions, step_costs

def goal_fn(state):
    return state[-1] == 'E'

path = pf.discrete_search(initial_state, expansion_fn, goal_fn) # A*
print(path)

Output:

[('A',), ('A', 'B'), ('B', 'C'), ('C', 'F'), ('F', 'D'), ('D', 'E')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM