I am working with a case of a client in which he applies the algorithm Problem of the backpack . I am using the code that I attached, it works more or less and has errors.
The example has 12 packages of different weights (which in their total weigh 1260 Kilos) with an associated value or price. The objective is to load the maximum number of packages, prioritizing the highest value without exceeding the maximum load of the truck.
For example;
1.- If the maximum load of the truck is 9 Kilos, this code should select Paquete 2 Peso :9 valor :160
and not Paquete 2 Peso :9 valor :150
(But it does not, select zero).
2.- On the other hand, if the maximum load of the truck is 500 Kilos, it will select the following:
Paquete 9 Peso :230 valor :591
Paquete 3 Peso :153 valor :200
Paquete 4 Peso :50 valor :160
Paquete 2 Peso :9 valor :160
Paquete 1 Peso :9 valor :150
Peso total paquetes: 451
Valor total paquetes: 1261
Does the job but not very well (7 and 5 would be missing to complete a load of 493)
3.- If the maximum load of the truck is 230, it will select the following:
Paquete 9 Peso :9 valor :230
If you do the work but wrong, because the best option would be the following:
Paquetes 1, 2, 4 y 5
Con un peso peso total de 83
y un valor valor total de 530
Since it is more efficient.
Code :
from itertools import takewhile
#Paquetes: "Nombre del paquete", Kilos, Precio
PAQUETES = (
("Paquete 1", 9, 150), ("Paquete 2", 9, 160), ("Paquete 3", 153, 200), ("Paquete 4", 50, 160),
("Paquete 5", 15, 60), ("Paquete 6", 66, 45), ("Paquete 7", 27, 60), ("Paquete 8", 39, 40),
("Paquete 9", 230, 591), ("Paquete 10", 520, 10), ("Paquete 11", 110, 70), ("Paquete 12", 32, 30))
def proceso_valor(item):
nombre, peso, valor = item
return float(valor)
def proceso_peso(item):
nombre, peso, valor = item
proceso_peso.peso_maximo -= peso
return proceso_peso.peso_maximo >= 0
#carga máxima del camión
proceso_peso.peso_maximo = 750
carga_lista = list(takewhile(proceso_peso, reversed(sorted(PAQUETES, key=proceso_valor))))
sumacarga = 0
sumavalor = 0
for item in carga_lista:
print item[0] + ' Peso :%i' % item[1] + ' valor :%i' % item[2]
sumacarga = sumacarga + item[1]
sumavalor = sumavalor + item[2]
print ''
print 'Peso total paquetes: %i' % sumacarga
print 'Valor total paquetes: %i' % sumavalor
There is something I am not seeing, I need help and the questions are: What makes my code not work with small maximum load values (9 or 100 for example)? and What mathematical operation is missing here to improve the result?