Created
January 11, 2020 14:24
-
-
Save manudatta/8a3c3988937d5ad7c8df0c4e9cb52ebd to your computer and use it in GitHub Desktop.
0-1 knapsack implementation in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: [email protected] | |
# zero-one knapsack implementation in python | |
items = { | |
'a': (12,4) | |
,'b':(10,6) | |
,'c':(8,5) | |
,'d':(11,7) | |
,'e':(14,3) | |
,'f':(7,1) | |
,'g':(9,6) | |
} | |
def knapsack(items, total_weight): | |
B = [0 for _ in range(0,total_weight+1)] | |
for (benefit,current_weight) in items: | |
print(B) | |
for weight in range(total_weight,current_weight-1,-1): | |
possible_benefit = B[weight-current_weight] + benefit | |
if possible_benefit >= B[weight] : | |
B[weight] = possible_benefit | |
return B | |
tuple_list = list(items.values()) | |
solution = knapsack(tuple_list,18) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment