Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

image text in transcribed
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)

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Introductory Relational Database Design For Business With Microsoft Access

Authors: Jonathan Eckstein, Bonnie R. Schultz

1st Edition

1119329418, 978-1119329411

More Books

Students also viewed these Databases questions