Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 4c7faa8

Browse files
authoredOct 24, 2024··
Create 01knapsack using branch and bound
Solving 0/1 knapsack problem using branch and bound
1 parent 6e24935 commit 4c7faa8

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
 

‎01knapsack

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
Function to solve 0/1 Knapsack problem with backtracking
2+
def knapsack_backtracking(weights,values,capacity,n):
3+
stack=[(0,0,0,[])]
4+
best_value=0
5+
best_items=[]
6+
while stack:
7+
current_index,current_weight,current_value,included_items=stack.pop()
8+
if current_index==n:
9+
if current_value>best_value:
10+
best_value=current_value
11+
best_items=included_items[:]
12+
continue
13+
stack.append((current_index+1,current_weight,current_value,included_items[:]))
14+
if current_weight+weights[current_index]<=capacity:
15+
new_list=included_items[:]
16+
new_list.append(current_index)
17+
stack.append((current_index+1,current_weight+weights[current_index],current_value+values
18+
[current_index],new_list))
19+
print("Items included (0-indexed):", best_items)
20+
return best_value
21+
n=int(input('Enter number of items:'))
22+
weights=[]
23+
values=[]
24+
for i in range(n):
25+
x=int(input(f"Enter weight of item-{i}:"))
26+
weights.append(x)
27+
y=int(input(f"Enter profit of item-{i}:"))
28+
values.append(y)
29+
print('weights:',weights)
30+
print('Values/profits:',values)
31+
capacity=int(input('Enter knapsack capacity:'))
32+
max_value=knapsack_backtracking(weights,values,capacity,n)
33+
print('The max profit is:',max_value)

0 commit comments

Comments
 (0)
Please sign in to comment.