Skip to content

Instantly share code, notes, and snippets.

@musshorn
Created July 5, 2013 09:25
Show Gist options
  • Save musshorn/5933260 to your computer and use it in GitHub Desktop.
Save musshorn/5933260 to your computer and use it in GitHub Desktop.
import numpy
v = values
w = weights
size = capacity + 1
#mat = numpy.zeros(shape=(size+1,len(v)+1))
mat = [ 0 ] * size
mold = [ 0 ] * size
incremented = [[ 0 ] * (len(v) + 1) for i in range(size)]
for x in range(1,len(v)+1):
for y in range(1,size):
mold[y] = mat[y]
if w[x - 1] <= y:
mat[y] = max(mat[y],mold[y - w[x - 1]] + v[x - 1])
if mat[y] > mold[y]:
incremented[y][x] = mat[y] - mold[y]
current = mat[size-1]
y = size - 1
x = len(v) -1
taken = []
temp = 0
while x >= 0:
print y,mat[y],mold[y]
if mat[y] != mold[y]:
taken.append(1)
mold[y-1] -= v[x]
y -= w[x]
else:
taken.append(0)
x -= 1
if x > 0:
for i in range(size):
mat[i] = mat[i] - incremented[i][x]
while len(taken) < len(v):
taken.insert(0,0)
taken.reverse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment