In a non-empty array of integers, the priority of a number is determined by the frequency of its occurrence. Elements are added as they come but the most frequent element is deleted first. If two elements have the same priority then the element which came first will be deleted first. For example: nums = [1,2,3,1,3,1,3,2,3]. After the first deletion now the array will be num=[1,2,1,1,2]. Implement a priority queue for the aforementioned scenario.
Answers
Code: [in Python language]
#a list for the data/array
l = list()
#a dictionary to record the frequency of each element
cd = dict()
#a loop to carry on with the program
while True:
print("1. Add elements")
print("2. View the updated array")
print("3. Exit")
print()
fc = int(input("Enter your choice: "))
#retrieving the data
if fc == 1:
n = int(input("Enter the number of elements you'd like to add: "))
print()
for i in range(n):
nm = int(input("Enter the element: "))
l.append(nm)
print()
print(l, "is your given array.")
elif fc == 2:
#recording the frequency/deleting the element with the most frequency
for i in l:
cd[i] = l.count(i)
x = max(cd.values())
for i in cd:
if cd[i] == x:
del cd[i]
break
l = list(filter((i).__ne__, l))
print(l, "is the updated array.")
elif fc == 3:
break