+ 3

Number of occurences

There is a list = [1,1,2,2,6] We need to find number of occurences of each element And print the list in order of decreasing occurence If occurences of two elements is same,the the greater number should preceed the smaller number d = {1:2,2:2,6:1} 1 and 2 have same number of occurences So, Final output should be : [2,1,6] I am able to get the occurences in a dictionary d = {'1':2,'2':2,'6':1} Then sort it in descending order and get the keys in a list Lst = [1,2,6] Now how to compare same occurences and print [2,1,6] ?

5th Jun 2020, 2:39 PM
Munib Ur Rahman
Munib Ur Rahman - avatar
10 ответов
+ 7
This version is using the Counter object, that is a specialized dictionary. https://code.sololearn.com/cJ7VgCNX9iKl/?ref=app
6th Jun 2020, 10:28 AM
Tibor Santa
Tibor Santa - avatar
+ 6
I would actually propose something à rebours - make a dictionary with occurences as keys and numbers as values. Then, when converting it back to a list, you can already sort by number of occurences first and then the values by magnitude. By the way - it sounded trivial at first, but wasn't that obvious :) https://code.sololearn.com/c0EMFvTjqzFb/?ref=app
5th Jun 2020, 3:50 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
Louis Excellent! 👍🏻 I love oneliners ;)
6th Jun 2020, 10:01 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
Kuba Siekierzyński Yes you are right, the reverse does all, better to write it like this. print([val for val,cnt in sorted(lt, key=lambda x: (-x[1], -x[0]))]) print([val for val,cnt in sorted(lt, key=lambda x: (-x[1], x[0]))]) print([val for val,cnt in sorted(lt, key=lambda x: (x[1], x[0]))]) print([val for val,cnt in sorted(lt, key=lambda x: (x[1], -x[0]))]) Here all 4 options are covered.
6th Jun 2020, 9:12 AM
Louis
Louis - avatar
+ 4
Thanks Kuba for the solution!!!
5th Jun 2020, 4:01 PM
Munib Ur Rahman
Munib Ur Rahman - avatar
+ 4
Python has a handy way of sorting a list of tuples, first by one item, then the other. https://code.sololearn.com/cWYnC4PcFR2A/?ref=app
6th Jun 2020, 7:24 AM
Louis
Louis - avatar
+ 3
We don't write code for you ,if you show us your attempt and ask a specific question , someone might help
5th Jun 2020, 2:43 PM
Abhay
Abhay - avatar
+ 3
Louis Nice! The only potential problem I see here is that you apply the same "reverse" parameter to both sorts. Not an issue here, but if you wanted to sort from the smallest number of occurences, but from the highest value, then it's not an option.
6th Jun 2020, 8:38 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 2
Help me with the final step if you know
5th Jun 2020, 2:49 PM
Munib Ur Rahman
Munib Ur Rahman - avatar
7th Jun 2020, 1:54 PM
Munib Ur Rahman
Munib Ur Rahman - avatar