0

Say I have a list (not necessarily sorted):

lst = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 10]

I need a function that returns count of unique elements in a list, in this case 10.

I am not allowed to use dict or set.

I thought about doing something like:

num = len(lst)
for e in lst:
    for i in lst:
        if e == i:
           num -= 1

But clearly, it does not work. Thanks!

12
  • which question is the same as this one? Commented Mar 29, 2015 at 3:31
  • Can you provide the output that you expect? Commented Mar 29, 2015 at 3:32
  • I am expecting 10 but I cannot use set. It has to use == and nothing else. That's the catch. Commented Mar 29, 2015 at 3:33
  • So you need to count number of unique values and you know that the list is sorted? Commented Mar 29, 2015 at 3:45
  • Sorted or not isn't relevant. Commented Mar 29, 2015 at 3:48

1 Answer 1

1

Try this:

Any solution that does a double nested loop over a list runs in O(n^2) time, the following runs in O(n log(n)) time. Though there might be a way to come with O(n) time solution without using a hash table, I don't see it.

def count_number_unique(my_list):
    prev = None
    unique_count = 0
    for ele in sorted(my_list):
        if ele != prev:
            unique_count += 1
        prev = ele
    return unique_count

Result:

In [20]: lst = [1, 1, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 10]

In [21]: count_number_unique(lst)
Out[21]: 10

In [22]: count_number_unique([1,2,1,9,1,2])
Out[22]: 3
Sign up to request clarification or add additional context in comments.

1 Comment

This function should return: 10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.