-3

So i want to do choose only the unique character of an array , the desired output is suppose to be :

Input : 4,5,6,4,2,2,9

Output : 5,6,9

I tried these code :

arr = [4,5,6,4,2,2,9]
unique = list(set(arr))

But the output is : 4,5,6,2,9

Is it possible to do it without numpy?

3 Answers3

1

You could calculate the frequency of the elements and pick the elements with frequency of one as follows.

from collections import Counter
arr = ...
unique = [k for k,v in Counter(arr).items() if v == 1]
  • Thank you it works, but can you actually tell me how Counter works? – Eugene Leo Jun 16 '20 at 09:20
  • Since counting is a common use case, Python provides the `Counter` class to facilitate counting. It is a subclass of `dict` that is specialized to count hashable objects and maintain the object frequency. As for how it counts, [it merely iterates thru the iterable and counts the elements](https://github.com/python/cpython/blob/e63cc2f64668bd1d4581f8efa7089af7e08863b8/Lib/collections/__init__.py#L478) :) For more details, please refer to its [docs](https://docs.python.org/3/library/collections.html?highlight=counter#collections.Counter). – Venkatesh-Prasad Ranganath Jun 16 '20 at 15:26
0

You can use counter from collections. Here is an example python code:

from collections import Counter
arr = [4,5,6,4,2,2,9]
d = Counter(arr)
unique = [x for x in d if d[x] == 1]
print(a)

Counter return a dictionary where, array item as a Key and item frequency as a value. For example, if array arr = [4,5,6,4,2,2,9] then counter provide following dictionary:

d = {
1: 2, 
2: 1, 
3: 1, 
4: 1,
5: 3,
6: 1
}
Ismail H Rana
  • 351
  • 1
  • 9
-1

What you're doing returns all numbers in the array, just without duplication. You can do what you want like this:

[x for x in array if array.count(x) == 1]

But thats not very efficient, because it needs to scan the entire array for every count() called. A faster way is:

from collections import defaultdict
counts = defaultdict(int)  # count how many times every number appears in the array, for example {5:1, 6:1, 9:1, 4:2, 2:2}. defaultdict(int) means that values default to 0.
for x in arr:
    counts[x] += 1
result = [number for number, count in counts.items() if count == 1 ]
Peter
  • 109
  • 5