01背包問題python 2.7實現


版權聲明:本文為博主原創文章,轉載請注明轉自 http://www.cnblogs.com/kdxb/p/6140625.html

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 class bag():
 4     def __init__(self,weight,value):
 5         self.weight = weight
 6         self.value = value
 7     def knapsack(self, full_weight):#weight value存數組
 8         result = [[0 for i in range(full_weight+1)] for i in range(len(self.value)+1)]
 9         count = len(self.weight)#物品個數
10         for n in range(1,count+1):#n當前最大物品個數
11             for weight in range(0,full_weight+1):#背包內重量遞增
12                 if self.weight[n-1]<=weight:#第n個背包的重量為weight[n-1]判斷是否小於允許容量
13                     if result[n-1][weight]<(result[n-1][weight-self.weight[n-1]]+self.value[n-1]):
14                         #如果當前物品在相同重量情況下價值更高
15                         result[n][weight]=result[n-1][weight-self.weight[n-1]]+self.value[n-1]
16                     else:
17                         result[n][weight]=result[n-1][weight]
18                 else:
19                     result[n][weight] =result[n-1][weight]
20         for perrow in result:
21             print perrow
22         return result
23     def find_which(self,full_weight):
24         result = self.knapsack(full_weight)
25         i= len(result)-1
26         j = len(result[i])-1
27         while i >=1:
28             while j>=1:
29                 if result[i-1][j]!=result[i][j]:#說明當前行的東西拿了
30                     print ''+ str(i)+''
31                     j = j -self.weight[i-1]
32                     i = i - 1
33                     break
34                 else:
35                     i = i -1
36 
37 
38 def main():
39     sort_instance = bag([2,2,6,5,4,1,2,7,5,7,4],[6,3,5,4,6,1,4,7,3,6,1])#重量,價值初始化
40     sort_instance.find_which(30)#定義背包總重量
41 
42 if __name__ =='__main__':
43     main()

實現結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM