0

How can I solve this problem in python. given a list of integers arr, write a function that returns true if and only if the number of occurrences of each value in the list is unique in python

So

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

Because number of 1s is 1, number of 2s are 2,,,

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

Because number of 1s is 1, number of 2s is 1

6 Answers6

2
def check_it(arr):
    occ = [arr.count(e) for e in set(arr)]
    return len(set(occ)) == len(occ)
moctarjallo
  • 1,479
  • 1
  • 16
  • 33
1

Seen on a different post : Checking if all elements in a list are unique

def func(arr):
     return len(arr) == len(set(arr)):
Avandale
  • 242
  • 1
  • 7
0

Suppose you have code like:

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9,]
arr2 = [1, 1, 2, 3, 4, 5, 5, 6, 7, 8, 9, 9,]

def contains_no_duplicates(arr):
    return len(arr) == len(set(arr))

print(contains_no_duplicates(arr))
print(contains_no_duplicates(arr2))

With output:

True
False

Taking the set of a list removes duplicates. This happens because each entry in a set must be unique in the same way that a dict cannot have a duplicate key.

thekid77777
  • 391
  • 1
  • 10
0

The naïve way is to put them all in a set, and rely on the set uniqueness guarantee to do the work.

If your list is huge, you're making a copy if it all, even if the first two elements are the same and would make the test fail. It's a really good, Pythonic solution. Nice, moctarjallo.

Another way is to use the set-hashed-lookup feature to quit early.

def all_unique(a):
    found = set()
    for item in a:
        if item in found:
            return False
        found.add(item)
    return False
Chad Miller
  • 1,435
  • 8
  • 11
0

The problem is to write a function that returns true if the number of occurrences of each value in the list is unique. So, for example

a=[1, 2, 2, 3, 3, 3] True number of 1s is 1, number of 2s are 2,,,

a=[1, 2, 3, 3] False number of 1s is 1, number of 2s is 1

0

For the occurences of the list to be unique we must find all the occurences. We can use the Counter from collections module for that. Then use a set to find unique elements and check its size.

from collections import Counter
ar  = [1,2]
ar2 = [1,2,2,3,3,3]
def is_unique(ar):
    occurence_list = Counter(ar).values()
    return len(occurence_list) == len(set(occurence_list))
print(is_unique(ar))
print(is_unique(ar2))

OUTPUT

False
True
Albin Paul
  • 3,330
  • 2
  • 14
  • 30