friskyewok
friskyewok

Reputation: 11

Count the unique elements in a list without set

I am currently attempting to make a program that will count and print the number of unique elements in a list.

My code:

def solution(N, A):
    yee = 1   

    for i in range(1, len(A)):
        j = 0
        for j in range(i):
            if(A[i] == A[j]):
                yee-=1
        if(i==j+1):
            yee +=1

    print(yee)


N = int(input())
A = []
n = 0
for e in input().split():
    if(n<N):
        A.append(int(e))
        n+=1

solution(N, A)

With the list containing (1 2 3 1 4 2 5 6 7 8) the output is supposed to be 6. However, my program is returning 8. I believe this is due to the program counting the 1 and 2, even though they are not technically unique in the problem. I'm sure it's and easy fix, but I just can't seem to figure it out. Any help would be greatly appreciated!!

Upvotes: 0

Views: 327

Answers (3)

Jack Robinson
Jack Robinson

Reputation: 106

As Green Cloak Guy said, you seem to be looking for the number of elements which appear exactly once, and his answer contains a solution to that. Here's a simple solution for finding the number of unique elements:

def unique_elements(A):
    return len([ 1 for (index, a) in enumerate(A) if A.index(a) == index ])

The idea here is to count up the first occurrence of each unique value.

  • enumerate allows us to get the index of the item, as well as the item itself, as we iterate;
  • A.index(a) gives the index of the first time the value of a appears in A.

So, if we count up all the times index equals A.index(a), we're counting the first time an item appears which has never appeared before, which is equal to the number of unique elements.

Upvotes: 0

Matt Reynolds
Matt Reynolds

Reputation: 477

Similarly if you need to keep check of the number of elements further on in your code, I like dictionary comprehension for this kind of problem:

dict_A = {x:A.count(x) for x in A}
print(len([x for x in dict_A if dict_A[x] == 1]))

Upvotes: 0

Green Cloak Guy
Green Cloak Guy

Reputation: 24691

The only way you would get the output of 6 for (1, 2, 3, 1, 4, 2, 5, 6, 7, 8) would be if you wanted to count the number of elements that appear exactly once, as opposed to the number of unique elements (there are 8 elements, of which two are repeated more than once).

You could do this in a one-liner:

def num_single_elements(A):
    return len(list(e for e in A if A.count(e) == 1))

Upvotes: 3

Related Questions