Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I have a route of a car but how can i make it simple(by using list)

I have a list like:

A=[(0, 16), (1, 11), (2, 4), (3, 14), (4, 8), (5, 15), (6, 13), (7, 2), (8, 20), (9, 17), (10, 5), (11, 12), (12, 6), (13, 7), (14, 0), (15, 1), (16, 19), (17, 18), (18, 10), (19, 9), (20, 3)]

This is a route of a car.For example this car leaves from 0 to 16(0,16) then it goes from 16 to 19(16,19) than it goes from 19 to 9 etc.
For big datasets it is hard to follow this route.
I try to write loops but couldn’t succeed.I have to convert this A list to another list like

B=[0,16,19,9,17,18,10,5,15,1,11,12,6,13,7,2,4,8,20,3,14,0]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

if you convert your list A to a dictionary the lookups are much faster:

A_dict = dict(A)

start = 0
route = [start]
frm = start
while True:
    to = A_dict[frm]
    route.append(to)
    frm = to
    if to == start:
        break
print(route)

for your given A you get the route

[0, 16, 19, 9, 17, 18, 10, 5, 15, 1, 11, 12, 6, 13, 7, 2, 4, 8, 20, 3, 14, 0]

the edges of your graph are stored in A_dict as

{0: 16, 1: 11, 2: 4, 3: 14, 4: 8, 5: 15, 6: 13, 7: 2, 8: 20, 9: 17, 10: 5, ...}

if you perform the lookup for the next hop in your list A the overall performance of your approach will be quadratic (in the length of the list A). the approach with the dictionary grows linearly in the length of A.


a slightly shorter version:

start = 0
route = [start]
while True:
    route.append(to := A_dict[route[-1]])
    if to == start:
        break
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading