Copyright NOTICE: This article for Bo Master original article, reprint please specify transfer from http://www.cnblogs.com/kdxb/p/6140625.html
1 #!/usr/bin/env python2 #-*-coding:utf-8-*-3 classbag ():4 def __init__(self,weight,value):5Self.weight =Weight6Self.value =value7 defKnapsack (self, full_weight):#weight Value Storage array8result = [[0 forIinchRange (full_weight+1)] forIinchRange (len (self.value) +1)]9Count = Len (self.weight)#Number of itemsTen forNinchRange (1,count+1):#N Current maximum number of items One forWeightinchRange (0,full_weight+1):#weight increment in backpack A ifSelf.weight[n-1]<=weight:#the nth backpack weighs weight[n-1] to determine if it is less than the allowable capacity - ifresult[n-1][weight]< (result[n-1][weight-self.weight[n-1]]+self.value[n-1]): - #if the current item is of higher value under the same weight theResult[n][weight]=result[n-1][weight-self.weight[n-1]]+self.value[n-1] - Else: -Result[n][weight]=result[n-1][weight] - Else: +Result[n][weight] =result[n-1][weight] - forPerrowinchResult: + PrintPerrow A returnresult at defFind_which (self,full_weight): -result =Self.knapsack (full_weight) -i= Len (Result)-1 -j = Len (Result[i])-1 - whileI >=1: - whileJ>=1: in ifRESULT[I-1][J]!=RESULT[I][J]:#something that shows the current line is taken. - Print 'Section'+ STR (i) +'a' toj = J-self.weight[i-1] +i = I-1 - Break the Else: *i = I-1 $ Panax Notoginseng - defMain (): theSort_instance = Bag ([2,2,6,5,4,1,2,7,5,7,4],[6,3,5,4,6,1,4,7,3,6,1])#weight, value initialization +Sort_instance.find_which (30)#define the total weight of the backpack A the if __name__=='__main__': +Main ()
Implementation results:
01 knapsack problem Python 2.7 implementation