web123456

01 Backpack problem (idea and python code)

  • import numpy as np
  • import pandas as pd
  • pf = [540, 200, 180, 350, 60, 150, 280, 450, 320, 120] # Profits of 10 Objects
  • w = [6, 3, 4, 5, 1, 2, 3, 5, 4, 2] # Weight of 10 objects
  • W = 30 # Maximum weight load for backpack
  • FF = [[0 for i in range(W)] for j in range(len(pf))] # DP two-dimensional array. FF
  • def initialize():
  • # Initialize the first column
  • MAX = 0
  • for i in range(len(FF)):
  • if w[i] == 1 and FF[i - 1][0] < pf[i]:
  • MAX = pf[i]
  • FF[i][0] = MAX
  • else:
  • FF[i][0] = MAX
  • # Initialize the first line
  • FF[0][w[0] - 1:] = [pf[0] for _ in range(len(FF[0][w[0]:]) + 1)]
  • def dynamic():
  • for j in range(1, W): # j+1 space
  • for i in range(1, len(pf)): # Top i+1 item
  • if w[i] > j + 1: # If you only put this new item, you can't put it down (don't forget that the w[i] here is real, while j is missing 1)
  • FF[i][j] = FF[i - 1][j]
  • elif w[i] == j + 1:
  • FF[i][j] = max(FF[i - 1][j], pf[i])
  • else:
  • FF[i][j] = max(FF[i - 1][j], pf[i] + FF[i - 1][j - w[i]])
  • if __name__ == '__main__':
  • initialize()
  • dynamic()
  • # Print the results
  • df = (FF)
  • = + 1
  • = + 1
  • print(df)