1. 程式人生 > 其它 >Python_揹包問題蠻力法解決(採用bin函式輔助生成集合子集)(bin函式實現)

Python_揹包問題蠻力法解決(採用bin函式輔助生成集合子集)(bin函式實現)

目錄

1.bgwt.py

import os
w = []
v = []
n = eval(input("輸入物品個數:"))
sw = eval(input("輸入揹包負重:"))

for i in range(n):
    tw = eval(input("輸入重量:"))
    w.append(tw)
    tv = eval(input("輸入價值:"))
    v.append(tv)

bnum = list(bin(2**n-1))
bnum.pop(0)
bnum.pop(0)
# 上面是在列表中刪除0b兩個字元,只保留二進位制

bitn = len(bnum)
#print(bnum)
#print(bitn)
ls = []

for i in range(2**n):
    tb = list(bin(i))
    tb.pop(0)
    tb.pop(0)
    #print(tb)
    ttb = []
    for j in range(len(tb)):
        ttb.append(eval(tb[j]))
    
    tb = ttb
    #print(tb)
    lentb = len(tb)
    for k in range(bitn - lentb):
        tb.insert(0,0)
    ls.append(tb)   #將每次生成的子集新增到ls子集集合列表中

print("全部子集如下:")
for i in range(2**n):
    print(ls[i])

flag = -1
maxvalue = 0
goodweight = 0

for i in range(2**n):
    tweight = 0
    tvalue = 0
    for j in range(n):
        if tweight >= sw:
            tweight = 0
            tvalue = 0
            break;
        elif ls[i][j] == 1:
            tweight = tweight + w[j]
            tvalue = tvalue + v[j]
    
    if maxvalue < tvalue and tweight <= sw:
        goodweight = tweight
        maxvalue = tvalue
        flag = i
#上面是獲得最佳集合,即最大價值且重量不超過揹包負重
#print(sw)

print("重量與對應價值:")
print(w)
print(v)
print("最好組合0/1為:")
print(ls[flag])
print("最佳重量:{0}".format(goodweight))
print("最高價值:{0}".format(maxvalue))

os.system("pause")

2.結果示例

物品5個,負重12

物品5個,負重15

物品6個,負重15