Skip to content

Commit 30eda4b

Browse files
authored
Added Knapsack Game
1 parent b31e425 commit 30eda4b

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

knapsack.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# KnapSack Problem
2+
3+
# This is a combinational optimization algorithm.
4+
5+
# In this algorithm, we will be given an array of values with its respective weights.
6+
# We will have a knapsack capacity. We will have to find the maximum value which is
7+
# less than the capacity .
8+
9+
# Note : We cannot break an item. Either we pick a whole item or we do not pick that.
10+
11+
12+
def knapsack(capacity, weights, values, size):
13+
14+
nums = [0 for i in range(capacity+1)]
15+
16+
for i in range(1, size+1):
17+
# starting backwards to store the value of the previous computation.
18+
for j in range(capacity, 0, -1):
19+
20+
# calculating the maximum value
21+
if weights[i-1] <= j:
22+
nums[j] = max(nums[j], nums[j-weights[i-1]]+values[i-1])
23+
24+
return nums[capacity]
25+
26+
27+
values = [] # array of the values
28+
weights = [] # array of the weighs
29+
30+
size = int(input("Enter the number of items to be inserted "))
31+
32+
for i in range(0, size):
33+
val = int(input("Enter value of item "))
34+
weight = int(input("Enter weight of item "))
35+
36+
values.append(val)
37+
weights.append(weight)
38+
39+
capacity = int(input("Enter the knapsack capacity "))
40+
41+
print("The maximum value is ", knapsack(capacity, weights, values, size))

0 commit comments

Comments
 (0)