+ 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] ?
10 Réponses
+ 7
This version is using the Counter object, that is a specialized dictionary.
https://code.sololearn.com/cJ7VgCNX9iKl/?ref=app
+ 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
+ 6
Louis Excellent! 👍🏻 I love oneliners ;)
+ 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.
+ 4
Thanks Kuba for the solution!!!
+ 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
+ 3
We don't write code for you ,if you show us your attempt and ask a specific question , someone might help
+ 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.
+ 2
Help me with the final step if you know