Sort Elements by Frequency

Given a list of elements and sort the elements according to its frequency. If 2 numbers have the same frequency then print the one which came first.

n = int(input())
li = list(map(int,input().split()))[:n]
d = {}
for ele in li:
  if ele not in d:
    d[ele] = li.count(ele)
result = []
while len(d)!=0:
  key = None
  val = None
  for k,v in d.items():
    if val==None or val<v:
      key = k
      val = v
  d.pop(key)
  result.extend([key]*val)
print(*result)
8
8 3 4 7 9 7 3 7

7 7 7 3 3 8 4 9

No comments:

Post a Comment

Total Pageviews