Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def knapsack(weights, values, weight_limit):
- best_values = [0] * (weight_limit + 1)
- for w in range(1, weight_limit + 1):
- best_val_for_weight = 0
- for i in range(len(weights)):
- if weights[i] <= w:
- prev_weight = w - weights[i]
- possible_best_weight = best_values[prev_weight] + values[i]
- if possible_best_weight > best_val_for_weight:
- best_val_for_weight = possible_best_weight
- best_values[w] = best_val_for_weight
- print('', w,':', best_values[w])
- itemWeights = [2, 4, 5]
- itemValues = [3, 6, 7]
- bagWeightLimit = 6
- knapsack(itemWeights, itemValues, bagWeightLimit)
Add Comment
Please, Sign In to add comment