01 Knapsack problem (Dynamic programming) Python implementation

Source: Internet
Author: User

In the 01 knapsack problem, choose whether to add an item to the backpack. It is necessary to compare the solution of the sub-problem of the item with the solution of the sub-problem of the item, which leads to a lot of overlapping sub-problems, which can be solved by using dynamic programming. N=5 is the number of items, c=10 is the weight of the bag can withstand, w=[2,2,6,5,4] is the weight of each item, v=[6,3,5,4,6] is the value of each item, first write the definition of recursion:


Then the bottom-up is implemented with code such as the following:

def bag (n,c,w,v): Res=[[-1 for J in Range (c+1)] for I in range (n+1)]for J in Range (c+1): Res[0][j]=0for i in range (1,n+1): fo R j in Range (1,c+1): Res[i][j]=res[i-1][j]if j>=w[i-1] and res[i][j]<res[i-1][j-w[i-1]]+v[i-1]:res[i][j]=res[ I-1][j-w[i-1]]+v[i-1]return resdef Show (n,c,w,res):p rint (' Maximum value: ', Res[n][c]) X=[false for I in range (n)]j=cfor i in Range (1,n+1): If Res[i][j]>res[i-1][j]:x[i-1]=truej-=w[i-1]print (' Selected item: ') for I in Range (n): if X[i]:p rint (' first ', I, ' A, ', end= ') print (') if __name__== ' __main__ ': N=5c=10w=[2,2,6,5,4]v=[6,3,5,4,6]res=bag (n,c,w,v) show (N,c,w,res)

The output results are as follows:



Reprint Please specify: Transfer from http://blog.csdn.net/littlethunder/article/details/26575417

01 Knapsack problem (Dynamic programming) Python 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.