0

I have a python list containing n elements, out of which n-1 are identical and 1 is not. I need to find the position of the distinct element.

For ex : Consider a python list [1,1,1,2,1,1]. I need the to find out the position of 2 in the list.

I can use a for loop to compare consecutive elements and then use two more for loops to compare those elements with the other elements. But is there a more efficient way to go about it or perhaps a built-in function which I am unaware of?

1
  • One way is to add the elements of the array to a set (which rejects duplicates). That set will contain exactly two elements. Pick one of them and count how many times it appears in the array. If that == 1, you found it. Otherwise its the other one. Commented Nov 23, 2015 at 1:38

3 Answers 3

1

Make a set out of it, then count those set elements' occurrences in the list and find the unique element's index() in it.

l = [1,1,1,2,1,1]
a,b = set(l)
if l.count(a) == 1:
    unique = l.index(a)
else:
    unique = l.index(b)

Result:

>>> unique
3
Sign up to request clarification or add additional context in comments.

2 Comments

Can be shortened to: a, b = set(l); unique = l.index(a if l.count(a) == 1 else b)
Or ...(a if l.count(a) - 1 else b), but I wasn't golfing. :)
1

You could use Counter, for example:

from collections import Counter

a = [1, 1, 1, 1, 2, 3, 3, 1, 1]
c = Counter(a)
for item, count in c.iteritems():
    if count == 1:
        print a.index(item)

This would print out 4, the index of 2 in the list a

Comments

0

Here's a slightly more efficient way (only goes through the list once instead of three times as in TigerhawkT3's answer), but not quite as clean:

def find_distinct_index(a):
    if len(a) < 3: raise ValueError("Too short of a list")
    if a[0] == a[1]:
        # it's neither the first nor the second element, so return
        # the index of the leftmost element that is *not* equal to 
        # the first element
        for i, el in enumerate(a):
            if el != a[0]: return i
        raise ValueError("List had no distinct elements")
    else:
        # it's either the first or the second. use the third to figure
        # out which to return
        return a[1] if a[0] == a[2] else a[0]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.