Home > Software design >  Python-3 - get values from list by frequency and then by the values with equal counts in descending
Python-3 - get values from list by frequency and then by the values with equal counts in descending

Time:05-01

I have list of integers, from which I would first like to get unique numbers, first ordered by their occurrences and then the numbers with equal counts should be ordered in descending order.

example 1:
input1 = [1,2,2,1,6,2,1,7]
expected output = [2,1,7,6]
explanation: both 2 and 1 appear thrice while 6 and 7 appear once. so, the numbers occurring thrice will be placed first and in descending order; and same for the set that appears once.

another example case:

input_2 = list(map(int, '40 29 2 44 30 79 46 85 118 66 113 52 55 63 48 99 123 51 110 66 40 115 107 46 6 114 36 99 13 108 85 39 14 121 42 37 56 11 104 28 24 123 63 51 118 52 120 28 64 43 44 86 42 71 101 78 93 1 6 14 42 33 88 107 35 70 74 30 54 76 27 91 115 71 63 103 94 109 39 4 16 108 97 83 29 57 86 121 53 94 28 7 5 31 123 21 2 17 112 104 75 124 88 30 108 14 65 118 28 81 80 14 14 107 21 60 47 97 50 53 19 112 43 46'.split()))
output_2 = list(map(int, '14 28 123 118 108 107 63 46 42 30 121 115 112 104 99 97 94 88 86 85 71 66 53 52 51 44 43 40 39 29 21 6 2 124 120 114 113 110 109 103 101 93 91 83 81 80 79 78 76 75 74 70 65 64 60 57 56 55 54 50 48 47 37 36 35 33 31 27 24 19 17 16 13 11 7 5 4 1'.split()))

This was from a coding test I took. This must be solved without using functions from imports like collections, itertools etc,. and using functions already available in python's namespace like dict, sorted is allowed. How do I do this as efficiently as possible?

CodePudding user response:

def sort_sort(input1):
    a = {}
    for i in input1:
        if i not in a:
            a[i]=1
        else:
            a[i]  =1
    b ={i:[] for i in set(a.values())}
    for k,v in a.items():
        b[v].append(k)      
    for v in b.values():
        v.sort(reverse=True)
    output=[]
    quays =list(b.keys())
    quays.sort(reverse=True)
    for q in quays:
        output  =b[q]
    print(output)
  • Related