How to find a unique element in the three-element array?

Viewed 211

I have a 3 element tuple where one of the elements is dissimilar from the other two. For example, it could be something like: (0.456, 0.768, 0.456).

What is the easiest way to find the index of this dissimilar element? One way I can think of is consider index (0, 1) and (1, 2) and one of these will be dissimilar. If it is (0, 1) then compare their elements to the element at 2 otherwise, compare elements of (1, 2) to index 0 to find the dissimilar element.

Feels like I am missing a pythonic way to do this.

4 Answers

A simple approach:

def func(arr):
    x, y, z = arr
    return 2 * (x == y) + (x == z)

Test:

func(['B', 'A', 'A'])
# 0

func(['A', 'B', 'A'])
# 1

func(['A', 'A', 'B'])
# 2

You could count the occurences of each element in the list then find the index of the place where only one element exists but I have a feeling this may not be as performant as your solution. It also wouldn't work if all 3 values are distinct.

my_tuple[[my_tuple.count(x) for x in my_tuple].index(1)]

You could try this:

index = [my_tuple.index(i) for i in my_tuple if my_tuple.count(i) == 1][0]

I'm not sure it is great performance-wise though.

What may look like A huge overkill in python 3, but couldn't help posting:

import collections
a = (0.768, 0.456, 0.456)
print("Dissimilar object index: ", a.index(list(collections.Counter(a).keys())[list(collections.Counter(a).values()).index(1)]))

Explanation:

collections.Counter(a): will return a frequency dict e.g {0.768:1, 0.456:2} etc. Then we just create a list to leverage index(1) to find out the value that's odd one out. Then we use a.index(odd_one_out_val) to find index.

Related