# A function that returns the frequency of each value:
def myFunc(e):
return cars.count(e)
cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi','Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
print(cars)
Output:
['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']
What I expect:
['BMW', 'VM', 'Mitsubishi', 'Mitsubishi', 'Ford', 'Ford', 'Ford']
Counts:
Ford - 3
Mitsubishi - 2
BMW - 1
VM - 1
It should sort in ascending order of count in the list.
>Solution :
The problem is that you are using cars inside the key function, but .sort is in-place. This causes cars to be unreliable in intermediate calls to the key function.
We can see the problem if we print cars inside the key function:
def myFunc(e):
print(cars)
return cars.count(e)
cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']
cars.sort(key=myFunc)
This outputs
[]
[]
[]
[]
[]
[]
[]
so cars.count will return 0 regardless what element is passed and the list will retain its original order.
Use sorted(...) which is not in-place:
def myFunc(e):
return cars.count(e)
cars = ['Ford', 'Ford', 'Ford', 'Mitsubishi', 'Mitsubishi', 'BMW', 'VW']
cars = sorted(cars, key=myFunc)
print(cars)
This outputs
['BMW', 'VW', 'Mitsubishi', 'Mitsubishi', 'Ford', 'Ford', 'Ford']
As a side-note, in this case you can use cars.count directly, without defining the wrapper function:
cars = sorted(cars, key=cars.count)