0-1 knapsack dynamic programming by Python

1382 단어 pythonleetcode
import os,sys

class knapsack01_dp:
    def __init__(self, w, v, C):
        self.w =w
        self.v = v
        self.C = C

    def solve(self):
        assert len(self.w) == len(self.v)
        if len(self.w) <= 0:
            return 0
        if self.C <= 0:
            return 0
        n = len(self.w)
        if n <= 0:
            return 0
        self.mem = []
        for i in range(len(w)):
            tmp_l = [0 for _ in range(C+1)]
            self.mem.append(tmp_l)
        for i in range(C+1):
            self.mem[0][i] = v[0] if i >= w[0] else 0
        for i in range(1, n):
            for j in range(self.C+1):
                self.mem[i][j] = self.mem[i-1][j]
                if j >= w[i]:
                    self.mem[i][j] = max(self.mem[i][j], self.mem[i-1][j-w[i]]+v[i])

        print("self.mem: {}".format(self.mem))
        return self.mem[n-1][self.C]

if __name__ == "__main__":
    w = list(range(20)) # each weight for 20 objs
    v = list(range(1, 101, 5)) # each value for 20 objs
    C = 200 # Capacity limitation
    k = knapsack01_dp(w, v, C) # Initlize a knapsack01 solver object
    max_v = k.solve() # get the max vale under given optimization constrains
    print("max_v: {}".format(max_v))    
    max_v = k.solve_opt()
    print("max_v: {}".format(max_v))
    

좋은 웹페이지 즐겨찾기