Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23160

Reordering a list of tuples to match the value of the next element in the list

$
0
0

If I have a list of tuples like this [(1, 3), (-6, 3), (1, 7)] and i would like to return a list like this [(7, 1),(1, 3), (3, -6)]. What can I do?, any ideas on how to sort the tuples. The essential condition is based on the fact that they "connect" by having the same value as the starting value in the next tuple.

I tried this code where I tried to place everything into a graph (adjacency list/dict) where each key is an element of the tuples and then i tried to arrange it following the conditions I mentioned previously but it is not working correctly. With inputs like the one given previously

list = [(1, 3), (-6, 3), (1, 7)]

the output was[(1, 3), (3, 7), (7, -6)]

instead of[(7, 1),(1, 3), (3, -6)]

this is the code i used

def compoundGraph(compounds):    graph = {}    for tuple in compounds:        if tuple[0] in graph:            graph[tuple[0]].append(tuple[1])        else:            graph[tuple[0]] = [tuple[1]]    return graphdef traverse(graph, start, visited, result):    if start not in visited:        visited.add(start)        result.append(start)        if start in graph:            for neighbor in graph[start]:                traverse(graph, neighbor, visited, result)def reorderCompounds(tuples_list):    graph = compoundGraph(tuples_list)    result = []    visited = set()    keys_copy = list(graph.keys())    for start in keys_copy:        traverse(graph, start, visited, result)    return [(result[i], result[i+1]) for i in range(len(result)-1)]list = [(1, 3), (-6, 3), (1, 7)]print(reorderCompounds(list))

If anyone has a more elegant or at least correct idea on how to tackle this problem, the help would be appreciated.


Viewing all articles
Browse latest Browse all 23160

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>