01 knapsack problem Python 2.7 implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.