简体   繁体   中英

What's the best way to do this in Python?

I have a list of objects where each of them have start and end properties like:

Item 0:
Start: 1
End: 12

Item 1:
Start: 6
End: 3

Item 2:
Start: 12
End: 6

I want to order them so that each item's start and end matches with the one that comes before and after itself, in the new list.

So in this example, it would be:

[Item 0] [Item 2] [Item 1]
[1   12] [12   6] [6    3]

It doesn't matter if the whole list was reversed.

Also there are 2 unrelated lists like above mixed in so I have to form 2 new lists that will have the proper order as shown above.

I am just gonna start implementing it "brute-force" so doing a lot of queries to create these lists but I wanted to ask if someone might have a more elegant way to solve this. I am not sure how common this sort of problem but I remember seeing this before, so maybe there are patterns to deal with this problem.

Assuming there are perfect match ups for start/end for each start and end:

items_by_start = dict((i.start, i) for i in your_items)

ordered_items = [your_items[0]]
for _ in xrange(len(your_items)-1):
    ordered_items.append(items_by_start[ordered_items[-1].end])

Ordering the elements suggests no duplicate items. However, with duplicate start s or end s you'd have to be more careful (and more than one solution might be possible). The problem would be equal to finding Eulerian paths in connected components of an undirected graph, which can be obtained by treating each ( start , end ) pair as a graph edge.

There are more than enough examples of how it can be implemented in Python on the web. Bear in mind, that it can be done easily in O(m) time, where m is the number of edges.

Also, an Euclidean path exists if and only if every vertex has an even degree. It still holds if you have many components in your graph.

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