Python program that uses a dictionary to find the frequency of each element in an array:

Created with Sketch.

Python program that uses a dictionary to find the frequency of each element in an array:

def frequency(arr):
    freq = {}
    for i in arr:
        if i in freq:
            freq[i] += 1
        else:
            freq[i] = 1
    return freq

# Example usage
arr = [1, 2, 3, 2, 4, 1, 5, 2, 1]
print(frequency(arr))

The function frequency(arr) takes an array as an argument. It first creates an empty dictionary freq. Then, it uses a for loop to iterate over the array, and for each element, it checks if the element already exists in the dictionary freq, if it does, it increases the value of the element by 1, otherwise it initializes the element with a value of 1. Finally, it returns the dictionary freq which contains the frequency of each element in the array.

The example usage creates an array and calls the frequency() function to find the frequency of each element in the array, and then it prints the resulting dictionary.

You could also use collections.Counter() method to find the frequency of each element in an array, this method is more efficient and pythonic way of counting the frequency of elements in an array.

from collections import Counter
def frequency(arr):
    return Counter(arr)

This method uses the Counter() method from the collections module to count the frequency of each element in the array and returns the dictionary containing the frequency of each element.

Leave a Reply

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