PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, June 28, 2022

[FIXED] How to sort edges of path based on start and end point?

 June 28, 2022     graph, networkx, python, sorting     No comments   

Issue

I have a problem with the path of each truck. From my model, I get the output of each truck path is misorder. I would like to order my list of edges based on the start and endpoint.

trucks =  {0: (10, 1),1:(7,1),2: (3, 10),3:(7,4)} # truck_number:(start_point, end_point) 

input I need to change:

  path = {0: [(2, 1), (5, 2), (6, 5), (10, 6)],
    1: [(2, 1), (5, 2), (6, 5), (7, 6)],
    2: [(2, 5), (3, 2), (5, 6), (6, 10)],
    3: [(5, 4), (6, 5), (7, 6)]}

output I need

output_i_need ={0: [(10, 6), (6, 5), (5, 2), (2, 1)],
                1: [(7, 6), (6, 5), (5, 2), (2, 1)],
                2: [(3, 2), (2, 5), (5, 6), (6, 10)],
                3: [(7, 6), (6, 5), (5, 4)]}

is there any library in python to order my list of edges?


Solution

I don't know of a library, but writing a function to reorder the list of edges is easy if you convert the list of edges into a dictionary mapping edge_start to edge_end.

trucks =  {0: (10, 1),1:(7,1),2: (3, 10),3:(7,4)} # truck_number:(start_point, end_point)
paths = {0: [(2, 1), (5, 2), (6, 5), (10, 6)],
    1: [(2, 1), (5, 2), (6, 5), (7, 6)],
    2: [(2, 5), (3, 2), (5, 6), (6, 10)],
    3: [(5, 4), (6, 5), (7, 6)]}

def reordered(l, start, end):
    d = dict(l)
    result = []
    while start != end:
        result.append((start, d[start]))
        start = d[start]
    return result

new_paths = { truck: reordered(path, trucks[truck][0], trucks[truck][1])
              for truck,path in paths.items() }

print(new_paths)
# {0: [(10, 6), (6, 5), (5, 2), (2, 1)],
#  1: [(7, 6), (6, 5), (5, 2), (2, 1)],
#  2: [(3, 2), (2, 5), (5, 6), (6, 10)],
#  3: [(7, 6), (6, 5), (5, 4)]}


Answered By - Stef
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing