Skip to content

Instantly share code, notes, and snippets.

@mshr-h
Last active January 5, 2016 07:22
Show Gist options
  • Save mshr-h/1227b38b4bd1e3fe45bb to your computer and use it in GitHub Desktop.
Save mshr-h/1227b38b4bd1e3fe45bb to your computer and use it in GitHub Desktop.
Knapsack problem
#-*- coding: utf-8 -*-
import sys
print("Input the item values:")
c = map(int, sys.stdin.readline().split(" "))
c.insert(0, 0)
print("Input the item sizes:")
a = map(int, sys.stdin.readline().split(" "))
a.insert(0, 0)
print("Input the bucket size:")
bucket_size = int(sys.stdin.readline())
table = [[0 for i in range(bucket_size + 1)] for j in range(len(c))]
for j in range(1, len(c)):
for k in range(0, bucket_size + 1):
table[j][k] = max(table[j-1][k], table[j-1][k-a[j]]+c[j]) if a[j]<=k else table[j-1][k]
print("Maximum value: "+str(table[-1][-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment