[EPI] The knapsack problem with Python [17.7]

 Reference:

http://rosettacode.org/wiki/Knapsack_problem/0-1#Dynamic_programming_solution

time   complexity: O(limit*len(items))

space complexity: O( limit )

 

def knapsack(items, limit):
    dp = [0] * (limit + 1)
    for i in range(len(items)):
        tmp, weight, value = items[i]
        j = limit
        while j >= weight:
            dp[j] = max( dp[j], dp[j - weight] + value )
            j -= 1
    return dp[limit]
# Here is the test
items = ( ("map", 9, 150), ("compass", 13, 35), ("water", 153, 200), ("sandwich", 50, 160), ("glucose", 15, 60), ("tin", 68, 45), ("banana", 27, 60), ("apple", 39, 40), ("cheese", 23, 30), ("beer", 52, 10), ("suntan cream", 11, 70), ("camera", 32, 30), ("t-shirt", 24, 15), ("trousers", 48, 10), ("umbrella", 73, 40), ("waterproof trousers", 42, 70), ("waterproof overclothes", 43, 75), ("note-case", 22, 80), ("sunglasses", 7, 20), ("towel", 18, 12), ("socks", 4, 50), ("book", 30, 10), )  
limit = 396
knapsack(items, limit)
# should return 1030

 

posted on 2014-09-05 10:16  AIDasr  阅读(290)  评论(0编辑  收藏  举报

导航