|
| 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