values = [ 4, 7, 10, 5, 3]
print (f' the max value is {max(values)} with index {values.index(max(values))}')
values [2]
the max value is 10 with index 2
weights = [15, 8, 2, 6, 12 ]
weights [2]
max_weight = sum(weights)
print (f' total weight of the knapsack will be {max_weight}')
total weight of the knapsack will be 43
current_value = 0
current_weight = 0
n= len(weights)
# set value to zero so we don't find it again
for item in range (0, n) :
print ('*******************************************************')
item_value = max(values)
print ('item value', item_value)
max_index = values.index(item_value)
item_weight = weights[max_index]
print (f"choose item {max_index +1} with max value {item_value} and weight {item_weight}")
if (current_weight + item_weight <= max_weight) :
print (f' add item number {item +1} to backpack with weight {item_weight}')
print (f' the bag is underweight ')
print (f' item {max_index + 1} was added to backpack with value = {item_value} ')
current_weight = current_weight + item_weight
current_value = current_value + item_value
print (f' current weight in backpack is {current_weight} with a value of {current_value}')
values[max_index] = 0
*******************************************************
item value 10
choose item 3 with max value 10 and weight 2
add item number 1 to backpack with weight 2
the bag is underweight
item 3 was added to backpack with value = 10
current weight in backpack is 2 with a value of 10
*******************************************************
item value 7
choose item 2 with max value 7 and weight 8
add item number 2 to backpack with weight 8
the bag is underweight
item 2 was added to backpack with value = 7
current weight in backpack is 10 with a value of 17
*******************************************************
item value 5
choose item 4 with max value 5 and weight 6
add item number 3 to backpack with weight 6
the bag is underweight
item 4 was added to backpack with value = 5
current weight in backpack is 16 with a value of 22
*******************************************************
item value 4
choose item 1 with max value 4 and weight 15
add item number 4 to backpack with weight 15
the bag is underweight
item 1 was added to backpack with value = 4
current weight in backpack is 31 with a value of 26
*******************************************************
item value 3
choose item 5 with max value 3 and weight 12
add item number 5 to backpack with weight 12
the bag is underweight
item 5 was added to backpack with value = 3
current weight in backpack is 43 with a value of 29
print (f' total weight is {current_weight} with a value of {current_value}')
total weight is 43 with a value of 29