Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Your code for this problem should be in a file called Knapsack-py. Imagine that

ID: 3733398 • Letter: Y

Question

Your code for this problem should be in a file called Knapsack-py. Imagine that you're invited to enter a vault and help yourself to as much as you can pack into your knapsack. Your knapsack, of course, has limited weight capacity. Each item in the vault is marked with its weight and value. Your objective is to select a subset of the items in the vault such that their total weight does not exceed your knapsack's capacity and such that the total value of the items that you choose is maximized. Each item can only be used once. Here is an example of us defining some items in Python: >rock [160, 4] u Heavy and low value " Light and very valuable! # Very light weight and some value > diamond [3, 25 spam [2, 1 >>> stuff " [rock, diamond, span) # now make a list of those items >> stuff (16e, 4], [3, 25), [2, 1] Of course, we could have just defined stuff directly as stuff" [ [16e, 4], [3, 25], [2, 111 Your job is to write a function knapsack(capacity, items) that takes a positive integer capacity and a list of items (such as stuff in the example above) where each item in the list is itself a list of the form [weight, value]. Then knapsack returns the best solution, which is maximum total value of items you can pack. Below is an example: > knapsack(5, stuff) knapsack capacity is s 26 .. The optimal value is 26 (uses the diamond and span) Of course, we could have also run this without first defining stuff as in: knapsack(s, 26 (6e, 4], [3, 25], (2, 1]1)

Explanation / Answer

# This is slight variation of standard 0-1 knapsack problem!
# In order to get you have to use Dynamic Programming and memoization.
# Go through the question properly.
# We use bottom up approach and save our results for future reference.

def knapSack(capacity, items):
    l=len(items)
    #Knap saves the computer values, it's like a 2-D array
    Knap = [[0 for c in range(capacity+1)] for c in range(l+1)]

    for i in range(l+1):
        for w in range(capacity+1):
            #for no value and no weight
            if i==0 or w==0:
                Knap[i][w] = 0
            # consider that we add the i'th item to sack
            elif items[i-1][0] <= w:
                Knap[i][w] = max(items[i-1][1] + Knap[i-1][w-items[i-1][0]], Knap[i-1][w])
            # consider that we don't add the item to sack  
            else:
                Knap[i][w] = Knap[i-1][w]
    #this is in fact max value for our capacity and weight
    return Knap[l][capacity]

#your input
stuff=[ [160,4], [3,25],[2,1]]
#python 3 output
print(knapSack(5,stuff))

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote