-1

I want to solve this question using dict in python.However i am not able to create code out of the logic. question says Given an array A[] of integers, sort the array according to frequency of elements. That is elements that have higher frequency come first. If frequencies of two elements are same, then smaller number comes first. Input: 2

5

5 5 4 6 4

5

9 9 9 2 5

Output:

4 4 5 5 6

9 9 9 2 5

t=int(input())
for i in range(t):
    n=int(input())
    arr=list(map(int,input().split()))
    d={}
    for i in arr:
        d[i]=d.get(0,i)+1
        a=max(d[i])
        print(i*d[i])
        a=a+1
Little bit of code that I tried is as above
  • 1
    try swapping `d[i]=d.get(0,i)+1` to `d[i]=d.get(i,0)+1` and remove the whole a=... stuff. Then proceed with the d.items() and sort it based on the values descending. – Patrick Artner Jun 29 '20 at 10:17
  • [edit] your question and tell us whats wrong with your code. Even better, what did you do to debug your code? Do you get what your coded code does and where it goes wrong? – Patrick Artner Jun 29 '20 at 10:20
  • 1
    Duplicate: [sort-list-by-frequency](https://stackoverflow.com/questions/25815377/sort-list-by-frequency) – Patrick Artner Jun 29 '20 at 10:22

1 Answers1

1
import collections

sample = [1, 9, 1, 1, 10, 10, 7, 1, 2, 2, 2, 0, 2, 3, 3, 4, 0, 5]
counter = collections.Counter(sample)

def helper_function(item):
    return counter[item], item  # returns a tuple

sorted_list = sorted(sample, key=helper_function)

# or if you prefer using lambda
sorted_list = sorted(sample, key=lambda item: (counter[item], item))


print(sorted_list)

Output:

[4, 5, 7, 9, 0, 0, 3, 3, 10, 10, 1, 1, 1, 1, 2, 2, 2, 2]
Vishal Singh
  • 6,014
  • 2
  • 17
  • 33