fork download
  1. def knapsack():
  2.  
  3. capacity = 41
  4.  
  5. matrix = [(1, 12.34, 123.99),(2, 23.45, 600.54),(3, 12.78, 90.67), (4, 9.34, 45.32)]
  6.  
  7. matrix = sorted(matrix, key=lambda object: object[1]/object[2])
  8.  
  9. i = 0
  10.  
  11. while capacity > 0:
  12.  
  13. if capacity > matrix[i][1]:
  14. capacity -= matrix[i][1]
  15. i+=1
  16. else:
  17. capacity = -capacity
  18.  
  19. output = ""
  20.  
  21. for k in range(0, i):
  22.  
  23. output += str(matrix[k][0]) + " "+ str(matrix[k][1]) + " " + str(matrix[k][2]) + " complete"
  24.  
  25. if capacity < 0:
  26.  
  27. output += str(matrix[i][0]) + " "+ str(matrix[i][1]) + " " + str(matrix[i][2]) + " "+ str(capacity) + "fractional"
  28.  
  29. print(output)
  30.  
  31. knapsack()
  32.  
Success #stdin #stdout 0.04s 9624KB
stdin
Standard input is empty
stdout
2 23.45 600.54 complete1 12.34 123.99 complete3 12.78 90.67 -5.210000000000001fractional