您的当前位置:首页多个背包问题--贪心算法-python

多个背包问题--贪心算法-python

来源:锐游网
import numpy as np

def greedy(p,weight,W):
    count_weight = 0
    count_p = 0
    value = []
    for i in range(len(p)):
        t = p[i]/weight[i]
        value.append(t)

    for i in range(len(W)):
        temp_p=p[:]
        temp_weight=weight[:]
        temp_value=value[:]
        for j in range(len(p)):
            x = np.array(temp_value)
            y = x.argsort()
            maxvalue=y[-1]
            if temp_weight[maxvalue]<=W[i]:
                W[i]=W[i]-temp_weight[maxvalue]
                count_weight=count_weight+temp_weight[maxvalue]
                count_p = count_p + temp_p[maxvalue]
                print("The",i+1,"back package contains items of", weight[maxvalue],"weight and", p[maxvalue] ,"value")
                p.pop(maxvalue)
                weight.pop(maxvalue)
                value.pop(maxvalue)
                temp_p = p[:]
                temp_weight = weight[:]
                temp_value = value[:]
            else:
                temp_p.pop(maxvalue)
                temp_weight.pop(maxvalue)
                temp_value.pop(maxvalue)
    print("The total weight is:",count_weight,"     The total value is:",count_p)

#test case 0:14
weight_0=[1,2,3,4,5,6]
value_0= [2,3,4,5,6,7]
knapsacks_0=[12]

#test case 1:14
weight_1=[4,5,6,7,1,3]
value_1= [3,4,5,5,2,3]
knapsacks_1=[10,2,1,6]

#test case 2:6
weight_2=[1,1,1,1,1,1]
value_2= [1,1,1,1,1,1]
knapsacks_2=[10,2,1,3]

#test case 3:20
weight_3=[1,2,3,4,5,6]
value_3= [2,3,4,5,6,7]
knapsacks_3=[10,2,6,3]

"""#test case 4:42
weight_4=[1,2,3,4,5,6,1,1,5,6,7,1,3,1,1,2,3,2,1,4]
value_4= [2,3,4,5,6,7,1,1,4,5,5,2,3,1,2,3,4,4,4,9]
knapsacks_4=[10,2,5,6,3,2]"""

#test case 5
weight_5=[35,30,60,50,40,
          10,25,54,26,75,
          24,75,78,33,16,
          65,26,56,89,58]
value_5= [10,40,30,50,35,
          40,30,31,22,17,
          22,56,85,33,64,
          86,80,57,38,45]
knapsacks_5=[165,184,148]

w = [3,4,4,3,4,5,3,6,7,3,4,5,5,5,6]
v = [5,6,6,3,4,5,3,6,6,1,2,3,4,3,3]
p = [8,9,10,11,12]

weight_4=[1,2,3,4,5,6,5,6,7,1]
value_4= [2,3,4,5,6,7,4,5,5,2]
knapsacks_4=[10,5,8]
#greedy(value_0,weight_0,knapsacks_0)
#greedy(v,w,p)

greedy(value_4,weight_4,knapsacks_4)

#greedy(value_1,weight_1,knapsacks_1)
#greedy(value_2,weight_2,knapsacks_2)
#greedy(value_3,weight_3,knapsacks_3)

因篇幅问题不能全部显示,请点此查看更多更全内容

Top