user14385051
user14385051

Reputation:

How to return unique elements in list of tuple as another tuple

Assume I have list of tuples a=[(0,1),(2,0),(1,4)] and I want to return unique element of each two tuples as a new tuple. For example (0,1) and (2,0) returns(1,2). Also (0,1) and (1,4) return (0,4).

Therefore, output is unique=[(1,2),(0,4)]

I tried code below but it seems I am not in correct path:

from itertools import combinations
a=[(0,1),(2,0),(1,4)]

b=list(combinations(a,2))
def myComp(pair1, pair2):
    if any(x == y for x, y in zip(pair1, pair2)):
        return(pair1,pair2)

d=[]
for i in range(len(b)):
    c=myComp(b[i][0],b[i][1])
    d.append(c) 

Upvotes: 0

Views: 900

Answers (3)

pho
pho

Reputation: 25479

First, convert all the tuples in a to sets.

a2 = [set(i) for i in a]

Then, take combinations of two elements of a2.

b2 = itertools.combinations(a2, 2)
# print(list(b2)) gives:
# [({0, 1}, {0, 2}), ({0, 1}, {1, 4}), ({0, 2}, {1, 4})]

Then, for every pair in b2, find the symmetric difference.

answer = [tuple(x ^ y) for x, y in b2]
# answer: [(1, 2), (0, 4), (0, 1, 2, 4)]

Like Ironkey mentions in the comments, you get (0, 1, 2, 4) in the last element because you're comparing (0, 2) and (1, 4), and all elements in these tuples are mutually exclusive.

To filter out the four-element tuples, you can simply add that condition:

answer_f = [x for x in answer if len(x) == 2]
# answer_f: [(1, 2), (0, 4)]

Upvotes: 2

coderoftheday
coderoftheday

Reputation: 2075

This doesn't use packages.

The conditions if i != x and a.index(i)<a.index(x) make sure we aren't comparing identical tuples and also we are comparing the same pair of tuples once

Then we just grab the element of they are not in the other tuple

The condition if len(m) == 2 and sorted(m) in uniq makes sure that the list is only 2 elements long, and also solves your comment about having (2,1) & (1,2)

a=[(0,1),(2,0),(1,4),(0,2)]

uniq = []
for i in a:
  for x in a:
    if i != x and a.index(i)<a.index(x):
      m = [y for y in i if y not in x] + [z for z in x if z not in i]
      if len(m) == 2 and tuple(sorted(m)) not in uniq:
        uniq.append(tuple(m))

print(uniq)

>>> [(1, 2), (0, 4)]

Upvotes: 1

Ironkey
Ironkey

Reputation: 2607

crude answer without any list comps:

from itertools import combinations

a = [(0,1),(0,2),(0,3),(1,2),(1,3),(1,4),(2,3)]

uniques = []
for x, y in combinations(a,2):
    z = []
    for i in x:
        if i not in y:
           z.append(i)
    for i in y:
        if i not in x:
           z.append(i)
    if len(z) == 2:
        uniques.append(tuple(z))

print(list(set(uniques)))
[(0, 1), (2, 4), (1, 2), (0, 4), (3, 4), (0, 3), (2, 3), (0, 2), (1, 3)]

Upvotes: 1

Related Questions