Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fb89d98

Browse files
authored
Create 0-1 Knapsack Using Brute Force Approach
1 parent 21b9ac0 commit fb89d98

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

‎0-1 Knapsack Brute Force Approach.py‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from itertools import combinations
2+
3+
def brute_force(number, capacity, weight_cost):
4+
best_cost = None
5+
best_combination = []
6+
7+
for i in range(1,number+1):
8+
for comb in combinations(weight_cost, i): #generate combinations of length from 1 to n
9+
temp = list(combinations(weight_cost, i))
10+
weight = sum(wc[0] for wc in comb) #Sum of all weights in combination
11+
cost = sum(wc[1] for wc in comb) #Sum of all costs in combination
12+
temp_index = []
13+
for item in comb:
14+
temp_index.append(weight_cost.index(item)+1)
15+
print('Combination: {} Weight = {} Cost = {}'.format(temp_index, weight, cost))
16+
if(best_cost is None or best_cost < cost) and weight <= capacity: #If best_cost is less, reinitialize the Knapsack
17+
best_cost = cost
18+
best_combination = [0]* number #Assign 0 to full array
19+
for wc in comb:
20+
best_combination[weight_cost.index(wc)] = 1 #Set the value to 1 which we want in KnapSack.
21+
return best_cost, best_combination
22+
23+
n = int(input('Enter number of elements in KnapSack: '))
24+
capacity = int(input('Enter capacity of KnapSack: '))
25+
26+
weight_cost = []
27+
28+
for i in range(n):
29+
weight = int(input('Enter weight of element {}: '.format(i+1)))
30+
cost = int(input('Enter cost of element {}: '.format(i+1)))
31+
weight_cost.append((weight, cost))
32+
33+
best_cost, best_combination = brute_force(n, capacity, weight_cost)
34+
35+
print('The best cost obtained is: {}'.format(best_cost))
36+
37+
print('The corresponding combination is: ')
38+
print(best_combination)
39+
element_list = []
40+
for i in range(len(best_combination)):
41+
if best_combination[i] == 1:
42+
element_list.append(i+1)
43+
44+
print('The selected elements are: ')
45+
print(element_list)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /