Finding the Frequency of Elements in an Array
Understanding Frequency Calculation
Finding the frequency of elements in an array involves counting the number of times each element appears.
We will explore three different methods to determine the frequency using Python.
Method 1: Using a Loop
This method iterates through the array and counts occurrences of each element.
def find_frequency(arr): visited = [False] * len(arr) for i in range(len(arr)): if visited[i]: continue count = 1 for j in range(i + 1, len(arr)): if arr[i] == arr[j]: count += 1 visited[j] = True print(f"{arr[i]} appears {count} times.") arr = [1, 2, 3, 2, 1, 3, 3] find_frequency(arr)
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.
Method 2: Using a Dictionary
This method utilizes a dictionary to store frequencies.
def find_frequency(arr): freq_map = {} for num in arr: freq_map[num] = freq_map.get(num, 0) + 1 for key, value in freq_map.items(): print(f"{key} appears {value} times.") arr = [1, 2, 3, 2, 1, 3, 3] find_frequency(arr)
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.
Method 3: Using Sorting
This method sorts the array first and then counts occurrences.
def find_frequency(arr): arr.sort() i = 0 while i < len(arr): count = 1 while i < len(arr) - 1 and arr[i] == arr[i + 1]: count += 1 i += 1 print(f"{arr[i]} appears {count} times.") i += 1 arr = [1, 2, 3, 2, 1, 3, 3] find_frequency(arr)
1 appears 2 times.
2 appears 2 times.
3 appears 3 times.