Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given n tuples representing pairs, return a list with connected tuples

Given n tuples, write a function that will return a list with connected values.

Example:

pairs = [(1,62),
    (1,192),
    (1,168),
    (64,449),
    (263,449),      
    (192,289),
    (128,263),
    (128,345),
    (3,10),
    (10,11)
    ]

result:

[[1,62,192,168,289],
 [64,449,263,128,345,449],
 [3,10,11]]     

I believe it could be solved using graphs or trees as data structure, creating nodes for each value and and edges for each pair with each tree or graph representing connected values, but I didn't find a solution yet.

What would be the best way to produce in python a result that yields a list of connected values for those pairs?

like image 736
Arian Pasquali Avatar asked Mar 11 '15 07:03

Arian Pasquali


People also ask

How do you get a list value's tuple form?

Just like list data structure, a tuple is homogenous. Therefore, a tuple can consist of elements of multiple data types at the same time. You can create a tuple by placing all elements inside the parentheses(()) separated by commas.

How do you combine two tuples?

Method #1 : Using + operator This is the most Pythonic and recommended method to perform this particular task. In this, we add two tuples and return the concatenated tuple. No previous tuple is changed in this process.

How do you convert a tuple to a list?

The most Pythonic way to convert a tuple to a list in Python is to call the built-in list() function and pass the tuple as a function argument to the function. The function list() takes any sequence type such as a tuple and converts them to lists. The return value of the function is the new list generated.


1 Answers

You also could use networkx as a dependency.

import networkx as nx

pairs = [(1,62),
        (1,192),
        (1,168),
        (64,449),
        (263,449),      
        (192,289),
        (128,263),
        (128,345),
        (3,10),
        (10,11)]


G = nx.Graph()
G.add_edges_from(pairs)
list(nx.connected_components(G))
like image 181
Giorgos Perakis Avatar answered Sep 21 '22 13:09

Giorgos Perakis