Вы также не удаляете добавленные значения из списка.Попробуйте добавить
values.pop(scores.index(valuable))
weights.pop(scores.index(valuable))
в строку до scores.pop(...)
.
Кроме того, вам нужно выйти из цикла, если добавленный элемент приведет к превышению емкости, например:
if (weight + weights[scores.index(valuable)]) > capacity:
break
Вам нужен код для работы с тай-брейками, который переназначает индекс очков на предмет с наивысшей ценностью, который подходит под емкость, например:
ties = [i for i, x in enumerate(scores) if x == valuable]
if len(ties) > 1:
most_valuable = -1
for idx in ties:
if values[idx] > most_valuable and (weight + weights[idx]) <= capacity:
most_valuable = values[idx]
scores_idx = idx
Полный код:
def knapsack(weights, values, capacity):
knapsack = []
scores = []
for i in range(len(values)):
score = values[i] - weights[i]
scores.append(score)
weight = 0
while weight < capacity:
if len(scores) != 0:
valuable = max(scores)
scores_idx = scores.index(valuable)
ties = [i for i, x in enumerate(scores) if x == valuable]
if len(ties) > 1:
most_valuable = -1
for idx in ties:
if values[idx] > most_valuable and (weight + weights[idx]) <= capacity:
most_valuable = values[idx]
scores_idx = idx
if (weight + weights[scores_idx]) > capacity:
break
knapsack.append(values[scores_idx])
weight += weights[scores_idx]
values.pop(scores_idx)
weights.pop(scores_idx)
scores.pop(scores_idx)
else:
break
return knapsack
# weights = [1, 2, 4, 2, 5]
# values = [5, 3, 5, 3, 2]
# capacity = 10
weights = [8, 2, 6, 7, 9]
values = [3, 11, 13, 7, 4]
capacity = 24
print(knapsack(weights, values, capacity))