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?
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.
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.
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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With