简体   繁体   中英

Unbounded Knapsack in Python

Consider the following problem statement:

Given a list of n integers, w={w1,w2,…,wn}, and another integer, W representing the expected sum. Select zero or more numbers from 'w' such that the sum of these numbers is as near as possible, but not exceeding, to the expected sum (W).

  • Each element of 'w' can be selected multiple times.

see code:

def KnapSack (i, w, X, W):
    if ( w[i:] == [] and X >= 0):
        return  ( W - X )   
    elif ( X < 0 ):
        return 0        
    else:       
        return max (KnapSack(i+1, w, X, W), KnapSack(i+1, w, X-w[i], W))

n, W = raw_input().split()
n, W = [int(n), int(W)]
w = map(int, raw_input().split())
print KnapSack (0, w[0:], W, W)

n and W, represent the length of list w and expected sum, respectively. Second line consists of n space separated integers, w1,w2,…,wn, representing the elements of list w.

I'm really having trouble with the unbounded condition that permits multiple selections from 'w'. Please help!

If each element can be selected multiple times, this is no longer knapsack-problem (that is NP hard), and can apply Bézout's identity that can be solved applying extended euclidean algorithm .

or you can just fix to somthing like

return max (KnapSack(i+1, w, X, W), KnapSack(i, w, X-w[i], W))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM