I have code like this:
def frequency_sorting(numbers):
return sorted(numbers, key=lambda i:numbers.count(i),reverse=True)
Alternatively:
def frequency_sorting(numbers):
return sorted(numbers, key=numbers.count,reverse=True)
When I call:
frequency_sorting([3,4,11,13,11,4,4,7,3])
Both give me:
[4, 4, 4, 3, 11, 11, 3, 13, 7]
I would expect:
[4, 4, 4, 3, 3, 11, 11, 13, 7]
I know how to solve the initial idea. I just need to understand in theory why my code does not work.
Your code does not work because both 11 and 3 (in your example) have the same count; the same priority for sorting.
So 3, 11
is an ordered sequence just like 11, 3
or 3, 3, 11, 11
or 3, 11, 3, 11
so are all correct and the choice is made by how the algorithm is implemented.
So you need to specify that the key of the order is not only the number of equal elements, but the the number of equal elements (with higher importance) and the element itself (if you want this). So if you want a reverse order for number of equal elements and (then) an order for the elements value you could just use:
sorted(numbers, key=lambda i:(-numbers.count(i),i))
or equally
sorted(numbers, key=lambda i:(numbers.count(i),-i),reverse=True)
You could want the order to be by number of elements and (then) first appearance of the element, in this case you can use:
sorted(numbers, key=lambda i:(-numbers.count(i),numbers.index(i)))
Or you can use something else; it depends on how you want to sort elements with same count but different value