I tried coding 0/1 Knapsack Dynamic programming bottom-up approach in Python.
Code that I tried:
def knapSack(W, wt, val, n):
matrix = [[0]*(W+1)]*(n+1)
print(matrix)
for i in range(n+1):
for j in range(W+1):
if i == 0 or j == 0:
matrix[i][j] = 0
elif wt[i-1] <= j:
matrix[i][j] = max(val[i-1]+matrix[i-1][j-wt[i-1]], matrix[i-1][j])
else:
matrix[i][j] = matrix[i-1][j]
return matrix[n][W]
def knapSack2(W, wt, val, n):
t = [[0 for i in range(W+1)] for j in range(n+1)]
print(t)
for i in range(n+1):
for j in range(W+1):
if i == 0 or j == 0:
t[i][j] = 0
elif wt[i - 1] <= j:
t[i][j] = max(val[i-1] + t[i-1][j - wt[i-1]], t[i-1][j])
else:
t[i][j] = t[i-1][j]
return t[n][W]
n = 3
W = 4
wt = [1, 2, 3]
val = [4, 5, 1]
print(knapSack(W, wt, val, n))
print(knapSack2(W, wt, val, n))
The output that I'm getting is:
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
16
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
9
Question: Why is there a difference in the output even if the Code for both the functions is exactly the same except declaration?
Like is there a difference between the following declarations even if the print function value is the same?
matrix = [[0]*(W+1)]*(n+1)
matrix = [[0 for i in range(W+1)] for j in range(n+1)]