Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
SSQ
GitHub Repository: SSQ/Coursera-Stanford-Greedy-Algorithms-Minimum-Spanning-Trees-and-Dynamic-Programming
Path: blob/master/Programming Assignment 4/knapsack_big.ipynb
423 views
Kernel: Python [conda env:DAND]

Knapsack Algorithm

1 point 2.This problem also asks you to solve a knapsack instance, but a much bigger one.

Download the text file below.

knapsack_big.txt This file describes a knapsack instance, and it has the following format:

[knapsack_size][number_of_items]

[value_1] [weight_1]

[value_2] [weight_2]

...

For example, the third line of the file is "50074 834558", indicating that the second item has value 50074 and size 834558, respectively. As before, you should assume that item weights and the knapsack capacity are integers.

This instance is so big that the straightforward iterative implemetation uses an infeasible amount of time and space. So you will have to be creative to compute an optimal solution. One idea is to go back to a recursive implementation, solving subproblems --- and, of course, caching the results to avoid redundant work --- only on an "as needed" basis. Also, be sure to think about appropriate data structures for storing and looking up solutions to subproblems.

In the box below, type in the value of the optimal solution.

ADVICE: If you're not getting the correct answer, try debugging your algorithm using some small test cases. And then post them to the discussion forum!

import numpy as np
# get the file path file_path = 'knapsack_big.txt' # file_path = 'test 1.txt' # convert text file to np.array type knapsack_big_data = np.loadtxt(file_path) int_knapsack_big_data = knapsack_big_data.astype(long)
knapsack_size = 2000000 items = 2000
def Knapsack_simplify(int_knapsack1_data, items, knapsack_size): A = np.zeros(shape=(2,knapsack_size+1)) for i in range(1,items+1): for x in range(knapsack_size+1): if int_knapsack1_data[i-1][1] > x: A[1][x] = A[0][x] else: A[1][x] = max(A[0][x],A[0][x-int_knapsack1_data[i-1][1]]+int_knapsack1_data[i-1][0]) A[0] = A[1] A[1] = np.zeros(shape=(1,knapsack_size+1)) return A[0][knapsack_size]
%%time print(Knapsack_simplify(int_knapsack_big_data, items, knapsack_size))
4243395.0 Wall time: 3h 15min 40s

Question 2 Answer:

4243395