* NOT HOMEWORK *
I implemented a backpack in python and successfully got the best value, but I would like to expand the problem to fill the table with all the appropriate values ββfor the satchel table of all weights and elements.
I implemented it in python, which I am new to, so please tell me if there is anything that I could improve, however the concepts should work in any language.
values, weights, table = [], [], [[]]
def knapsack(i, W):
global weights, values, table, counter
if (i < 0):
return 0
if (weights[i] > W):
return knapsack(i - 1, W)
else:
return max(knapsack(i - 1, W), values[i] + knapsack(i - 1, W - weights[i]))
def main():
global values, weights, table
W = int(input())
values = list(map(int, input().split()))
weights = list(map(int, input().split()))
table = [[0 for i in range(W)] for i in range(len(values))]
for i in range(len(values)):
for j in range(W):
table[i][j] = 0
print("Result: {}".format(knapsack(len(values) - 1, W)))
printKnapsack(W)
if __name__ == '__main__':
main()
I also have this print table method, which is not related, but so that you can see that I output it as:
def printLine(W):
print(" ",end="")
for i in range(W + 1):
print("-----",end="")
print("")
def printKnapsack(W):
global table
print("\nKnapsack Table:")
printLine(W)
print("| k\w |", end="")
for i in range(W):
print("{0: >3} |".format(i + 1), end="")
print("")
printLine(W)
for i in range(len(values)):
print("| {} |".format(i+1), end="")
for j in range(W):
print("{0: >3} |".format(table[i][j]), end="")
print("")
printLine(W)
This is an example input:
10
18 9 12 25
5 2 4 6
This is what should be output:
Result: 37
Knapsack Table:
-------------------------------------------------------
| k\w | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
-------------------------------------------------------
| 1 | 0 | 0 | 0 | 0 | 18 | 18 | 18 | 18 | 18 | 18 |
-------------------------------------------------------
| 2 | 0 | 9 | 9 | 9 | 18 | 18 | 27 | 27 | 27 | 27 |
-------------------------------------------------------
| 3 | 0 | 9 | 9 | 12 | 18 | 21 | 27 | 27 | 30 | 30 |
-------------------------------------------------------
| 4 | 0 | 9 | 9 | 12 | 18 | 25 | 27 | 34 | 34 | 37 |
-------------------------------------------------------
knapsack(i, W), , , , , , .
, .
def knapsack(i, W):
global weights, values, table, counter
if (i < 0):
return 0
if (weights[i] > W):
table[?][?] = ?
return knapsack(i - 1, W)
else:
table[?][?] = ?
return max(knapsack(i - 1, W), values[i] + knapsack(i - 1, W - weights[i]))