Unique Number of Occurrences in Python



Suppose we have an array, and we need to check whether each element has a unique number of occurrences. If no such element exists, we return false; otherwise, we return true. For example, given the array [1, 1, 2, 2, 2, 3, 4, 4, 4, 4], the function will return true because no two elements have the same number of occurrences: 1 occurs twice, 2 occurs three times, 3 occurs once, and 4 occurs four times.

Various Techniques to Find Unique Occurrences

Following are the various techniques to find the unique occurrence of the elements in a list ?

Using a Dictionary to Find the Unique Occurrences

In Python, a dictionary is a built-in data type that stores data in key-value pairs. It is an unordered, mutable, and indexed collection. Each key in a dictionary is unique and maps to a value. Dictionaries are often used to store data that is related, such as information associated with a specific entity or object, where you can quickly retrieve a value based on its key.

Algorithm

Following are the steps to find the unique occurrences using a dictionary ?

  • We need to initialize an empty dictionary and append it with each value with its frequency.
  • If the element is not present in the dictionary, add it with value 1
  • If the element is present in the dictionary, increment its value by 1
  • We need to initialize another dictionary to track the frequencies.
  • And iterate through each key-value pair in the dictionary
  • If the frequency is already present in another dictionary, return False otherwise, add the frequency 1.
  • If all the frequencies are unique returns, True.

Example

Following is an example of finding the unique number of occurrences using a dictionary ?

class Solution(object):
   def uniqueOccurrences(self, arr):
      d = {}
      for i in arr:
         if i not in d:
            d[i] =1
         else:
            d[i]+=1
      l = {}
      for x, y in d.items():
         if y in l:
            return False
         l[y] = 1
      return True
ob1 = Solution()
print(ob1.uniqueOccurrences([1,1,2,2,2,3,4,4,4,4]))

Following is the output of the above code ?

True

Using two Lists to find the Unique Occurrences

A list is one of the built-in data types in Python, used to store a sequence of items. A Python list is defined by enclosing comma-separated items within square brackets `[ ]`. The items in a list can be of different data types. Each item in the list can be accessed using its unique index, which starts at 0.

Algorithm

Following are the steps to find the unique number of occurrences using the list ?

  • Initialize two lists, unique_elements is used to store unique elements, and the count_list to store the count of the elements.
  • We need to iterate through the given sequence. If the element is not present in the unique_elements we need to append the element.
  • We need to find the occurrences of each unique element of the unique_elements list in an array and append it to the count_list.
  • Create another empty list to track the unique occurrence. Iterate through each element in the count_list and if the element is not present in the unique_list append the element else return False
  • If all counts are unique, return True.

Example

Following is an example to find the unique number of occurrences using the list ?

def Unique_Occurances(arr):
    list_1 = []
    count = []
    # Create a list of unique elements
    for i in arr:
        if i not in list_1:
            list_1.append(i)
    # Count the occurrences of each unique element
    for i in list_1:
        count.append(arr.count(i))
    # Check if all counts are unique
    unique_count = []
    for i in count:
        if i in unique_count:
            return False  # If a count is already in unique_count, it's not unique
        unique_count.append(i)
    return True  # All counts are unique
	
# Correct function call
print(Unique_Occurances([1,2,2,2,3,4,4,4,4]))

Following is the output of the above code ?

False

Using Counter to Find Unique Occurences

Python Counter is a container that holds a count of objects. It is used to count items available or existing in iterables. Counts are allowed to be any integer value including zero or negative counts.

The counter is a subclass of the dictionary. It represents data as a key and value. It inherits all the methods and properties of the dictionary. It allows to perform arithmetic and set operations. It can be used with any iterable which implements iteration protocol.

Following is the syntax of the Python Counter- 

class collections.Counter([iterable-or-mapping])

Example

In the following example, we have counted the occurrences of each element using a Counter function from the collection module. The uniqueOccurrences() function returns True if the counts are unique, otherwise; False ?

from collections import Counter
def uniqueOccurrences(arr):
    counts = Counter(arr)  # Count occurrences of each element
    return len(set(counts.values())) == len(counts.values())  # Check if counts are unique

print(uniqueOccurrences([10, 20, 20, 30, 30, 30, 40, 40, 40, 40]))

Following is the output of the above code ?

True

Using 'set' and Manual Counting

In Python, a set is an unordered collection of unique elements. Unlike lists or tuples, sets do not allow duplicate values i.e. each element in a set must be unique. Sets are mutable, meaning you can add or remove items after a set has been created.

Sets are defined using curly braces {} or the built-in set() function. They are particularly useful for membership testing, removing duplicates from a sequence, and performing common mathematical set operations like union, intersection, and difference.

Example

In the following example, we have defined a function of uniqueOccurrences() that checks whether the number of occurrences of each element in the given list is unique. The function first creates a dictionary count to store the occurrence of each unique element in the list using dictionary comprehension. Then, it compares the length of the set of occurrence values with the total number of values to ensure all occurrences are distinct. If they match, the function returns True, indicating unique occurrences; otherwise, it returns False.

def uniqueOccurrences(arr):
    counts = {num: arr.count(num) for num in set(arr)}  # Count occurrences for each unique element
    return len(set(counts.values())) == len(counts.values())  # Check for uniqueness

print(uniqueOccurrences([10, 1, 20, 20, 20, 35, 40, 45, 40, 40]))

Following is the output of the above code ?

False
Updated on: 2024-12-20T17:35:36+05:30

769 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements