I am trying to write different implementations for a fractional knapsack problem.
For this I have 2 arrays:
- Values
- Weights
The elements value[n] corresponds to element weights[n]. So we can calculate value_per_unit as:
for I in range(values):
value_per_unit.append(values[I]/weights[I])
value_per_unit.sort()
I now need the 2 arrays (values and weights) to be sorted according to the value_per_unit array
eg: If
- values = [60, 100, 120]
- weights = [20, 50, 30]
Then
values_per_unit = [3.0, 2.0, 4.0]
and so values_per_unit_sorted will be [2.0, 3.0, 4.0]
I need the values and weights arrays to become:
- values_sorted = [100,60,120]
- weights_sorted = [50,20,30]
Is there a way to achieve this using simple lambda functions?
I can still do something like this, but it seems highly inefficient every-time I need to access the elements:
weights[(value_per_unit_sorted.index(max(value_per_unit_sorted)))]