Write a python program to count the frequency of a given element in a list of numbers.
Answers
Explanation:
#Initialize array.
arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];
#Array fr will store frequencies of element.
fr = [None] * len(arr);
visited = -1;
for i in range(0, len(arr)):
count = 1;
for j in range(i+1, len(arr)):
╚═══❖•ೋ° ANSWER °ೋ•❖═══╝
In this program, we have an array of elements to count the occurrence of its each element. One of the approaches to resolve this problem is to maintain one array to store the counts of each element of the array. Loop through the array and count the occurrence of each element as frequency and store it in another array fr.
1 2 8 3 2 2 2 5 1
In the given array, 1 has appeared two times, so its frequency is 2, and 2 has appeared four times so have frequency 4 and so on.
#Initialize array
arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];
#Array fr will store frequencies of element
fr = [None] * len(arr);
visited = -1;
for i in range(0, len(arr)):
count = 1;
for j in range(i+1, len(arr)):
if(arr[i] == arr[j]):
count = count + 1;
#To avoid counting same element again
fr[j] = visited;
if(fr[i] != visited):
fr[i] = count;
#Displays the frequency of each element present in array
print("---------------------");
print(" Element | Frequency");
print("---------------------");
for i in range(0, len(fr)):
if(fr[i] != visited):
print(" " + str(arr[i]) + " | " + str(fr[i]));
print("---------------------");
Element | Frequency
----------------------------------------
1 | 2
2 | 4
8 | 1
3 | 1
5 | 1