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