+ 2

Sorting Elements of an Array by Frequency

Please refer this site for question https://practice.geeksforgeeks.org/problems/sorting-elements-of-an-array-by-frequency/0# Could you please tell me the difference between the 2 codes . This is my code https://code.sololearn.com/cPCqohHluwGK/#py This is the code in comment section passed all testcases https://code.sololearn.com/c8NELN6dzKZ8/#py And what wrong in my code.

27th Oct 2020, 3:05 PM
Varshith
Varshith - avatar
4 Antworten
+ 1
Obviously the results are sorted by key and then by frequency and not the other way. So for some reason the code seems to behave differently in their runtime environment. First I would try swapping the indices Other things to try: - Save the sorted dict to a new variable - create another dict with freq as key and list as values, for the example that would be {3:[4,6], 4:[5], 6:[3], 7:[1,2,7]}. Should be easier to loop over - print intermediate results like the dict after sorting to better understand what's happening
28th Oct 2020, 7:59 AM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Did you correct your code? It gives correct results for me. I think you had the indices swapped in your lambda function when you tested it. Nice solution btw
27th Oct 2020, 9:39 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Oh and you can ditch the reverse parameter if you negate the values in the lambda function like lambda x: (-x[1],x[0])
27th Oct 2020, 9:43 PM
Benjamin Jürgens
Benjamin Jürgens - avatar
0
Benjamin Jürgens still the same testcase failed for me after changing the code in the lambda . But I think using (key = lambda x:(x[1],-x[0]),reverse = True) and (key = lambda x:(-x[1],x[0])) both results the same.
28th Oct 2020, 3:12 AM
Varshith
Varshith - avatar