Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Way of making a set of tuple in which the order of tuple doesn't matters

I want to make a set of tuples in which the order of tuples shouldn't matter. For eg.- If the tuples I want to add is :

[(1,2),(1,3),(2,1)]

It should output like this:

{(1,2),(1,3)}

Is there any efficient way of doing this in python?

like image 530
shivank01 Avatar asked Jun 28 '18 11:06

shivank01


People also ask

Which is the efficient way to change a value in tuple?

Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.

Is the order of data maintained in tuple set?

A tuple is an ordered collection of items. An ordered collection keeps the items in the order you insert or initialize them. In other words, the order is preserved. This is in contrast to dictionaries or sets, where the order is not preserved (unordered collections).

How do you order a set of tuples in Python?

Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.

Does order matter for tuples?

For all intents and purposes, it does not matter, and the use of ordered tuples is just the convention.


1 Answers

You can apply sorted and then tuple, followed by conversion to set:

res = set(map(tuple, map(sorted, L)))

print(res)

{(1, 2), (1, 3)}

Explanation

There are a couple of good reasons why you should not convert each tuple to set as an initial step:

  1. Tuples (1, 1, 2) and (1, 2) would become equal after conversion to set.
  2. Even in the case where we are considering tuples of length 2, we would be adding an assumption that tuple({(1, 2)}) and tuple({(2, 1)}) are equal. While this may be true, it would be considered an implementation detail, since set is considered to be unordered.

Function composition

Function composition is not native to Python, but if you have access to the 3rd party toolz library you can avoid nested map:

from toolz import compose

tup_sort = compose(tuple, sorted)

res = set(map(tup_sort, L))
like image 78
jpp Avatar answered Sep 19 '22 17:09

jpp