Implement dynamic programming solution for Knapsack.

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

View File

@@ -1,42 +1,17 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
from collections import namedtuple
Item = namedtuple("Item", ['index', 'value', 'weight'])
import knapsack
def solve_it(input_data):
# Modify this code to run your optimization algorithm
# parse the input
lines = input_data.split('\n')
firstLine = lines[0].split()
item_count = int(firstLine[0])
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
k = knapsack.input_data_to_knapsack(input_data)
if k.count * k.capacity < 50000000:
r = knapsack.solve_knapsack_dynamic(k)
else:
r = knapsack.solve_knapsack_greedy(k)
return knapsack.result_to_output_data(r)
if __name__ == '__main__':
@@ -47,5 +22,7 @@ if __name__ == '__main__':
input_data = input_data_file.read()
print(solve_it(input_data))
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)")