简体   繁体   中英

Knapsack Python function

I have this question regarding the knapsack problem and the aim is pretty much similar to the outcome of the knapsack problem. The question is:

Suppose you have a collection of n items. All the items have the same weight, w and you can choose at most one of each item. Write a Python function, which is given as input the capacity of the knapsack, capacity , a list (sorted in ascending order) of values, values , of each item, and the weight, w and returns the maximum value that the knapsack can hold.

I have tried writing out the function but somehow I couldn't figure out where would the weight, w , will be suitable in the line of code.

def knapsack(capacity,n):
    if len(n) ==0:
          return 0
    elif n[-1][0] > capacity:
          return knapsack(capacity, n[:-1])
    else:
          return max(knapsack(capacity,n[:-1]), knapsack(capacity-n[-1][0],n[:-1]+n[-1][1]

Somehow, I searched a lot of ways to figure out this question as I'm relatively new to Python, but I didn't like the way the code works as I haven't figured out the question entirely. Is there a much better way to solve this Python function?

If they all have the same weight, then that makes the problem quite trivial.

You simply have to sort the items by their value in descending order, and start choosing items from the list until either you have no more items in the list of values, or you have run out of capacity to store more.

Note that the problem states that the values are sorted in ascending order of value. Since the list is already sorted in ascending order, you can simply reverse the list to have the items appear in descending order of value. This will give you the item with the largest value first.

Starting from the first item, keep choosing items until you can no longer fit them in your knapsack.

def knapsack(capacity, values):
    values.reverse()
    num_items = capacity // w
    return sum(values[:num_items])

num_items holds the maximum number of items we can fit in the knapsack. values[:num_items] uses array slicing to retrieve atmost num_items values from the array, then finally we pass this to sum function to calculate the maximum sum

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