Implement dynamic programming solution for Knapsack.

This commit is contained in:
Felix Martin 2019-11-26 03:38:28 -05:00
parent e3a7b12a79
commit fd8ce084e6
2 changed files with 100 additions and 34 deletions

89
knapsack/knapsack.py Normal file
View File

@ -0,0 +1,89 @@
from collections import namedtuple
Result = namedtuple("Result", ['objective', 'is_optimal', 'xs'])
Item = namedtuple("Item", ['index', 'value', 'weight'])
Knapsack = namedtuple("Knapsack", ['count', 'capacity', 'items'])
def solve_knapsack_greedy(knapsack):
remaining_capacity = knapsack.capacity
current_value = 0
xs = [0] * knapsack.count
for item in knapsack.items:
if remaining_capacity >= item.weight:
remaining_capacity -= item.weight
current_value += item.value
xs[item.index] = 1
return Result(current_value, 0, xs)
def solve_knapsack_dynamic(knapsack):
value_column = [0 for _ in range(knapsack.capacity + 1)]
# Keep track for each item for what capacities we take
# the respective item. This allows us to backtrack the items
# for the optimal solution later.
item_taken = {i: set() for i in range(len(knapsack.items))}
for item in knapsack.items:
new_column = list(value_column)
for capacity in range(knapsack.capacity + 1):
if item.weight <= capacity:
# Calculate the new value for the capacity if we take the item.
new_value = item.value + value_column[capacity - item.weight]
if new_value > value_column[capacity]:
new_column[capacity] = new_value
item_taken[item.index].add(capacity)
# There is no else case because new_colum contains the right values
# from the previous item so we only have to update when the new
# value is better.
value_column = new_column
objective = value_column[-1]
# Dynamic programing computes the best posible solution.
is_optimal = 1
# Reconstruct which items are used for the optimal solution.
xs = []
current_index = knapsack.items[-1].index
current_capacity = knapsack.capacity
while current_index >= 0:
if current_capacity in item_taken[current_index]:
current_capacity -= knapsack.items[current_index].weight
xs.append(1)
else:
xs.append(0)
current_index -= 1
xs.reverse()
return Result(objective, is_optimal, xs)
def solve_knapsack_depth_first_search(knapsack):
objective = 0
pass
def input_data_to_knapsack(input_data):
lines = input_data.split('\n')
item_count, capacity = map(int, lines[0].split())
items = []
for i in range(1, item_count + 1):
line = lines[i]
value, weight = map(int, line.split())
items.append(Item(i-1, value, weight))
k = Knapsack(item_count, capacity, items)
return k
def result_to_output_data(result):
# prepare the solution in the specified output format
output_data = str(result.objective) + ' ' + str(result.is_optimal) + '\n'
output_data += ' '.join(map(str, result.xs))
return output_data

View File

@ -1,42 +1,17 @@
#!/usr/bin/python #!/usr/bin/python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from collections import namedtuple import knapsack
Item = namedtuple("Item", ['index', 'value', 'weight'])
def solve_it(input_data): def solve_it(input_data):
# Modify this code to run your optimization algorithm # Modify this code to run your optimization algorithm
k = knapsack.input_data_to_knapsack(input_data)
# parse the input if k.count * k.capacity < 50000000:
lines = input_data.split('\n') r = knapsack.solve_knapsack_dynamic(k)
else:
firstLine = lines[0].split() r = knapsack.solve_knapsack_greedy(k)
item_count = int(firstLine[0]) return knapsack.result_to_output_data(r)
capacity = int(firstLine[1])
items = []
for i in range(1, item_count+1):
line = lines[i]
parts = line.split()
items.append(Item(i-1, int(parts[0]), int(parts[1])))
# a trivial greedy algorithm for filling the knapsack
# it takes items in-order until the knapsack is full
value = 0
weight = 0
taken = [0]*len(items)
for item in items:
if weight + item.weight <= capacity:
taken[item.index] = 1
value += item.value
weight += item.weight
# prepare the solution in the specified output format
output_data = str(value) + ' ' + str(0) + '\n'
output_data += ' '.join(map(str, taken))
return output_data
if __name__ == '__main__': if __name__ == '__main__':
@ -47,5 +22,7 @@ if __name__ == '__main__':
input_data = input_data_file.read() input_data = input_data_file.read()
print(solve_it(input_data)) print(solve_it(input_data))
else: else:
print('This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)') print("This test requires an input file. "
"Please select one from the data directory. "
"(i.e. python solver.py ./data/ks_4_0)")