0

I have an input list like [1,2,2,1,6] the task in hand is to sort by the frequency. I have solved this question and am getting the output as [1,2,6]. But the caveat is that if two of the numbers have the same count like count(1) == count(2). So the desired output is [2,1,6] then in the output array, 2 must come before 1 as 2 > 1.

So for the input [1,1,2,2,3,3] the output should be [3,2,1]. The counts are the same so they got sorted by their actual values.

This is what I did

input format:

  1. number of Test cases
  2. The list input.
def fun(l):
    d = {}
    for i in l:
        if i in d:
            d[i] += 1 
        else:
            d[i] = 1 
    d1 = sorted(d,key = lambda k: d[k], reverse=True)

    return d1
try:
    test = int(input())
    ans = []
    while test:
        l = [int(x) for x in input().split()]
        ans.append(fun(l))
        test -= 1
    for i in ans:
        for j in i:

            print(j, end = " ")
        print()    
except:
    pass

1 Answer 1

2

I think that this can help you. I added reverse parameter that is setting by default to True, because that gives the solution, but I wrote in the code where you can edit this as you may.

Here is the code:

from collections import defaultdict # To use a dictionary, but initialized with a default value

def fun(l, reverse = True):
    d = defaultdict(int)    
    # Add count
    for i in l:
        d[i] += 1 

    # Create a dictionary where keys are values
    new_d = defaultdict(list)
    for key,value in d.items(): 
        new_d[value].append(key)

    # Get frequencies
    list_freq = list(new_d.keys())
    list_freq.sort(reverse = reverse) #YOU CAN CHANGE THIS
    list_freq

    # Add numbers in decreasing order by frequency
    # If two integers have the same frequency, the greater number goes first
    ordered_list = []
    for number in list_freq:
        values_number = new_d[number]
        values_number.sort(reverse = reverse) # YOU CAN CHANGE THIS
        ordered_list.extend(values_number)

    return ordered_list

Examples:

l = [1,2,2,1,6]
fun(l)
#Output [2,1,6]

I hope this can help you!

Sign up to request clarification or add additional context in comments.

2 Comments

In this case, i will take another approach, not to use your exactly function fun
can you explain a bit why we have to pass reverse = False

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.