Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"python.linting.pylintEnabled": false,
"python.formatting.provider": "black"
}
36 changes: 31 additions & 5 deletions knapsack.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,35 @@
import sys
from collections import namedtuple

Item = namedtuple('Item', ['index', 'size', 'value'])

Item = namedtuple('Item', ['index', 'size', 'value', 'ratio'])

# okay so let's try to implement the brute-force version
# I don't know why but I keep going in circles with this one
#



# greedy version--seems to work
def knapsack_solver(items, capacity):
# !!!! IMPLEMENT ME
pass
items_sorted_by_ratios = (sorted(items, key=lambda x: x.ratio))
knapsack = []
total_value = 0
total_weight = 0
avail_weight = capacity

for i in reversed(items_sorted_by_ratios):
if i.size <= avail_weight:
knapsack.append(i)
avail_weight -= i.size
total_value += i.value
total_weight += i.size
knapsack.append(['total value: ', total_value])
knapsack.append(['total weight: ', total_weight])
return knapsack




if __name__ == '__main__':
if len(sys.argv) > 1:
Expand All @@ -18,9 +42,11 @@ def knapsack_solver(items, capacity):

for line in file_contents.readlines():
data = line.rstrip().split()
items.append(Item(int(data[0]), int(data[1]), int(data[2])))
items.append(Item(int(data[0]), int(data[1]), int(data[2]), int(data[2]) / int(data[1])))

file_contents.close()
print(knapsack_solver(items, capacity))
print("Here are the contents of your knapsack: ")
for i in knapsack_solver(items, capacity):
print(i)
else:
print('Usage: knapsack.py [filename] [capacity]')
Binary file added pseudocode_et_al/knapsack1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added pseudocode_et_al/namedtuples.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.