Advertisement
Guest User

shortest_path.py

a guest
Aug 16th, 2024
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. from copy import copy
  2. from math import inf
  3.  
  4. def get_distance (a,b,connections):
  5.     for con in connections:
  6.         if (con[0]==a) and (con[1]==b):
  7.             return con[2]
  8.     return None
  9.  
  10. def get_path_distance (path,connections):
  11.     if None==path:
  12.         return None
  13.     ret=0
  14.     i=0
  15.     while (i<(len(path)-1)):
  16.         a=path[i]
  17.         b=path[i+1]
  18.         d=get_distance(a,b,connections)
  19.         if d==None:
  20.             return None
  21.         ret+=d
  22.         i+=1
  23.     return ret
  24.  
  25. def select_origin (origin, connections):
  26.     ret=[]
  27.     for con in connections:
  28.         if con[0]==origin:
  29.             ret.append(con)
  30.     return ret
  31.  
  32. def get_path (destiny, connections, step, path):
  33.     if step==0:
  34.         return path
  35.     if path[-1]==destiny:
  36.         return path
  37.     origin=path[-1]
  38.     ap=select_origin(origin,connections)
  39.     ret=None
  40.     note=inf
  41.     for p in ap:
  42.           if p[1] in path:
  43.               continue
  44.           path2=copy(path)
  45.           path2.append(p[1])
  46.           path2=get_path(destiny,connections,step-1,path2)
  47.           if path2==None:
  48.               continue
  49.           n=get_path_distance(path2,connections)
  50.           if n<note:
  51.               note=n
  52.               ret=path2
  53.     return ret
  54.  
  55. def main():
  56.     origin=input("Enter the name of the origin:")
  57.     destiny=input("Enter the name of the destiny:")
  58.     ncon=int(input("Enter the number of connections:"))
  59.     connections=[]
  60.     for _ in range(ncon):
  61.         s=input("Enter origin,destiny,distance:")
  62.         l=s.split(",")
  63.         l[2]=float(l[2])
  64.         connections.append(l)
  65.     path=[origin]
  66.     path=get_path(destiny,connections,ncon,path)
  67.     if path:
  68.         print(path)
  69.     else:
  70.         print("It is impossible.")
  71.  
  72. main()
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement