Counting Frequencies of Elements in an Array Using Hashing in Python

 

 

This Python program counts the frequencies of elements in an array using a hash table (dictionary). Hashing allows us to efficiently track the occurrences of each element in the array.

Program Structure

  • Function Definition: The program defines a function named count_frequencies that takes an array as input.
  • Hash Table: A dictionary is used to store elements as keys and their corresponding frequencies as values.
  • Iteration: The program iterates through the array, updating the frequency count in the dictionary for each element.
  • Output: Finally, it prints the elements along with their frequencies.

Python Program


def count_frequencies(arr):
    """
    Count the frequency of elements in the given array.

    Parameters:
    arr (list): A list of elements.

    Returns:
    dict: A dictionary with elements as keys and their frequencies as values.
    """
    # Create an empty dictionary to store frequencies
    frequency = {}

    # Iterate over each element in the array
    for element in arr:
        # Update the frequency count
        if element in frequency:
            frequency[element] += 1
        else:
            frequency[element] = 1

    return frequency

# Example usage
if __name__ == "__main__":
    # Sample array
    array = [1, 2, 2, 3, 3, 3, 4, 5, 5, 5, 5]
    
    # Count frequencies
    freq = count_frequencies(array)
    
    # Print the frequencies
    print("Element frequencies:")
    for key, value in freq.items():
        print(f"Element {key}: {value}")

How It Works

  1. The function count_frequencies takes an array as an argument.
  2. A dictionary named frequency is initialized to store the counts.
  3. As we iterate through the array, we check if the element is already in the dictionary:
    • If it is, we increment its count.
    • If not, we add it to the dictionary with a count of 1.
  4. After processing all elements, the function returns the dictionary containing the frequencies.
  5. The example at the end shows how to use the function and prints the results.

Conclusion

This simple and efficient program demonstrates how to count the frequency of elements in an array using hashing. Using a dictionary allows for average-case constant time complexity for insertions and lookups, making the program efficient even for large datasets.

 

Leave a Reply

Your email address will not be published. Required fields are marked *