HackerRank - LonelyInteger

Viewed 51

I am a beginner to coding, and I am wondering why my code below doesn't work. The problem is from HackerRank - LonelyInteger, it is to identify the unique number in an array where other numbers occur twice.

For example, the input of [1, 2, 3, 4, 3, 1, 2] would give the result of 4.

May I ask why doesn't my code below work?

My thinking is to create a new 'test' list to store the numbers. When there is a new number, the 'test' list store that number, and when it encounters the number again, it deletes that number, leaving behind the unique number. However, when I run the code, the list is empty. Can anyone explain why is this?

def lonely_integer(a):
    test = []
    for i in a:
        if i not in test:
            test.append(i)
        if i in test:
            test.remove(i)
    print(test)


lonely_integer([1, 1, 2])
1 Answers

There's probably a better way but you can do this by making a set from your list. Then iterate over the set counting the number of occurrences of each value. If a value occurs once then it's "lonely"

a = [1, 2, 3, 4, 3, 1, 2]

def lonely_integer(a):
    for v in set(a):
        if a.count(v) == 1:
            return v
print(lonely_integer(a))

You could also use a Counter as follows:

from collections import Counter

def lonely_integer(a):
    for k, v in Counter(a).items():
        if v == 1:
            return k

Output:

4
Related