Python Challenge - The Knapsack Problem

This community-built FAQ covers the “The Knapsack Problem” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge The Knapsack Problem

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

def knapsack(weight_cap, weights, values):
  wvDict = dict(zip(weights, values))
  weights.sort(reverse = True)
  MAX_POTS = 10
  potsWeight = [0 for _ in range(MAX_POTS)]
  potsValue = [0 for _ in range(MAX_POTS)]

  for i in weights:
    for j in range(MAX_POTS):
      if i<=weight_cap-potsWeight[j]:
        potsWeight[j] += i
        potsValue[j] += wvDict.get(i)
  print(potsValue, potsWeight)
  return max(potsValue)

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))
from itertools import combinations
def knapsack(weight_cap, weights, values):
    variandid = []
    uus = []
    kaal = 0
    vaartus = 0
    max_value = 0
    for i in range(1, len(values)+1):
        variandid += combinations([el for el in range(len(values))], i)
    for rida in variandid:
        uus = list(rida)
        for i in uus:
            kaal += weights[i]
            vaartus += values[i]
            if kaal > weight_cap:
        if kaal <=weight_cap:
            if vaartus > max_value:
                max_value = vaartus
        kaal = 0
        vaartus = 0
    return max_value
def knapsack(weight_cap, weights, values):
  # Write your code here
  # amount of values beign added
  # amount = 1 to add two
  amount = -1;
  tots = [];
  for i in range(len(weights)):
    amount += 1;
    if amount == 0:
      for i3 in range(len(weights)):
        if weights[i3] <= weight_cap:
          #print(values[i3], " \t", amount)
      for count in range(len(weights)-amount):
        for c2 in range(count+amount, len(weights)):
          total_weight = weights[count];
          total_value = values[count];
          #print(count, " ", c2)
          if amount > 1:
            for i2 in range(1,amount+1):
              #print(count, "\t", c2, "\t",i2)
              total_weight+= weights[count-i2]
              total_value += values[count-i2]
            total_weight+= weights[c2];
            total_value+= values[c2]
          #print(total_value, "\t", amount)
          if total_weight <= weight_cap:
  return max(tots)

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))
import copy
from itertools import product
from copy import deepcopy
def knapsack(weight_cap, weights, values):
    # Write your code here
    weight_value_dict = {}
    for w, v in zip(weights, values):
        if weight_value_dict.get(w, 0):  # in dict
        else:  # not in dict
            weight_value_dict[w] = [v]

    weight_combination = []
    weight = sorted(weights, reverse=True)
    p = product([0, 1], repeat=len(weight)) # 0:no_carry, 1:carry
    for _ in p:
        cap = weight_cap
        for i, w in zip(_, weight):
            if i:
                cap -= w
            if cap < 0:
    max_value = 0
    for group in weight_combination:
        sum = 0
        for i, w in zip(group, weight):
            wvd = copy.deepcopy(weight_value_dict)
            if i: # same weight differ value
                b = wvd[w]
                sum += b.pop()

        max_value = max(max_value, sum)

    return max_value

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))
def knapsack(weight_cap, weights, values):

  max_value = 0
  for i in range(len(weights)):
    if weights[i] < weight_cap:
      if max_value < values[i]:
        max_value = values[i]
      for j in range(i+1,len(weights)):
        k = j
        cur_weight = weights[i]
        cur_value = values[i]
        while k < len(weights) and cur_weight + weights[k] <= weight_cap:
          cur_value += values[k]
          cur_weight += weights[k]
          if cur_value > max_value:
            max_value = cur_value
          k += 1
  return max_value

weight_cap = 10
weights = [3,6,8]
values = [50,60,100]
print(knapsack(weight_cap, weights, values))

Explanation at the bottom of the code. Nice challenge!

from itertools import combinations

def knapsack(weight_cap, weights, values):
  dic = dict(zip(weights, values))
  output = sum([list(map(list, combinations(weights, i))) for i in range(len(weights) + 1)], [])
  max = 0
  for o in output:
    if sum(o) <= weight_cap:
      comb_tot = 0
      for i in range(len(o)):
        comb_tot += dic.get(o[i])
      if comb_tot > max:
        max = comb_tot
  return max

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))

# Create a dictionary with which value each weight has
# Create a list of all possible combinations of the weights
# Check for each possible combination that is not heavier than the capacity, 
# what tot value is has and find out the highest combination.
def knapsack(weight_cap, weights, values):
  from itertools import chain, combinations

  # Turn the weights and values into a dictionary.
  weight_dict = {weights[i]: values[i] for i in range(len(weights))}

  # All combinations of items.
  possibilities = chain.from_iterable(combinations(weight_dict.keys(), i) for i in range(1,len(weights)+1))

  # Filter to the combinations less than the weight cap.
  possibilities = filter(lambda x:sum(x) <= weight_cap, possibilities)

  # A function that returns the value of an item combination.
  def get_value(some_items):
    value = 0
    for i in some_items:
      value += weight_dict[i]
    return value

  # Return the maximum value.
  return max(get_value(items) for items in possibilities)  

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))

(1) Turn the weight-values into a dictionary.
(2) Find all possible combinations of items.
(3) Filter the combinations to only those less than the weight cap.
(4) Calculate the values of the plausible combinations and return the max.

i had a solution then kept combining them in list comprehensions and this is what ended. cant recognise it now but looks cool

def knapsack(weight_cap, weights, values): # create key, value pair for weights, values dict_of_weights_values = dict(zip(weights, values)) # find combinations of weights <= weight_cap item_combinations = [] for i in range(1, len(weights)): item_combinations.extend([list(x) for x in combinations(weights,i) if sum(x) <= weight_cap]) # get value in each item combination item_combinations_values = [0] for i in item_combinations: current_sum = 0 for j in i: current_sum += dict_of_weights_values[j] item_combinations_values.append(current_sum) return max(item_combinations_values)

def powerset(s):
x = len(s)
powersetlist =
for i in range(1 << x):
powersetlist.append([s[j] for j in range(x) if (i & (1 << j))])
return powersetlist
def knapsack(weight_cap, weights, values):

List all subsets of weights.

powersetweights = list(powerset(weights))

Create new set of Total values from viable subsets

Totals =

Check each subset total.

for i in range(len(powersetweights)):
if sum(powersetweights[i]) <= weight_cap:
# Create list for matching values
valuelist =
# Run through weights from powerset and match to values in given set, then add to valuelist
for j in range(len(powersetweights[i])):
return max(Totals)

weight_cap = 20
weights = [3, 6, 8, 9, 10]
values = [50, 60, 100, 110, 140, 150]
print(knapsack(weight_cap, weights, values))

def knapsack(weight_cap, weights, values):
    # Create a table of zeros to store the optimal values
    table = [[0 for x in range(weight_cap + 1)] for x in range(len(values) + 1)]

    # Build the table
    for i in range(1, len(values) + 1):
        for w in range(0, weight_cap + 1):
            if weights[i - 1] <= w:
                table[i][w] = max(values[i - 1] + table[i - 1][w - weights[i - 1]], table[i - 1][w])
                table[i][w] = table[i - 1][w]

    # Return the last entry in the table
    return table[len(values)][weight_cap]

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))

I used an inefficient, but simplistic algorithm:
Iterate through all the combinations, and if the sum of the weights for that combination is at or below weight_cap, then include the sum of the values (from that combination) when calculating the maximum value.
It’s O(2^n).

I made a generator function to get an iterator corresponding to a combination denoted by an integer’s binary representation (in reverse).
And a function that gets the sums of a list (or iterable) of pairs.

def get_iterator_by_binary(x, arr):
  # x is an integer denoting a combination from list arr
  i = 0
  b = 1
  while (b <= x):
    if ((b & x) == b):
      yield arr[i];
    b = b << 1
    i += 1

def sums(pairs_list):
  sum1 = 0
  sum2 = 0
  for a, b in pairs_list:
    sum1 += a
    sum2 += b
  return (sum1, sum2)

def knapsack(weight_cap, weights, values):
  zipped = list(zip(weights, values))
  length = len(zipped)
  max_so_far = 0
  index_of_max = 0
  for i in range(1, 2 ** length):
    weight, value = sums(get_iterator_by_binary(i, zipped))
    if (weight <= weight_cap) and (value > max_so_far):
      max_so_far = value
      index_of_max = i
  return max_so_far

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100] 
print(knapsack(weight_cap, weights, values))  # 110 

can some one please inform me why this code does not pass all the test? I know it is very convoluted, but i wanted to solve this problem recursively. Thank you for anyone that manages to tell me

def knapsack(weight_cap, weights, values):
result=(knapsack_list(weight_cap, weights, values,0))
if result==:
if weights[-1]<=weight_cap:
return max(result)

def knapsack_list(weight_cap, weights, values,stolen=0):
for i in range(len(values)):
if rest_weight==0:
if rest_weight<0:
elif rest_weight>0:
return result

weight_cap = 100
weights = [3, 6, 8, 5, 7, 3, 2, 7,2]
values = [50, 60, 100, 30, 50, 60, 30, 80,30]
print(knapsack(weight_cap, weights, values))

def knapsack(weight_cap, weights, values):
if (len(weights) == 0):
return 0
# optimal solution if we don’t include first item:
wgtIfNotInclude = knapsack(weight_cap, weights[1:], values[1:])
if (weights[0] <= weight_cap):
# optimal solution if we do include it (if we can):
wgtIfInclude = values[0] + knapsack(weight_cap - weights[0], weights[1:], values[1:])
return max(wgtIfInclude, wgtIfNotInclude)
return wgtIfNotInclude

weight_cap = 10
weights = [3, 6, 8]
values = [50, 60, 100]
print(knapsack(weight_cap, weights, values))

def knapsack(weight_cap, weights, values): from itertools import combinations from numpy import Inf combos = [] vals = [] max_val = -Inf for L in range(len(weights)): for combo in combinations(weights,L): if combo and sum(combo) <= weight_cap: combos.append(combo) for combo in combos: val = 0 for e in combo: i = weights.index(e) val += values[i] if val > max_val: max_val = val vals.append(max_val) if vals: return vals[-1] else: return 0 weight_cap = 10 weights = [3, 6, 8] values = [50, 60, 100] print(knapsack(weight_cap, weights, values))
from itertools import combinations def knapsack(weight_cap, weights, values): weight_values = dict(zip(weights, values)) comb_weights = [] #fill array with possible combinations for i in range(1, len(weights)): for subset in combinations(weights, i): comb_weights.append(subset) comb_values = [] #filter out all possible combinations and append respective value to array for element in comb_weights: value_sum = 0 if sum(element) <= weight_cap: for i in element: value_sum += weight_values[i] comb_values.append(value_sum) #return highest value return max(comb_values, default=0) weight_cap = 10 weights = [3, 6, 8] values = [50, 60, 100] print(knapsack(weight_cap, weights, values))

For the code I used the combinations tool from itertools. It helps finding all possible combinations of weights. Then the code filters out all combinations that the knapsack can actually carry. For each of this combinations the respective value is appended into an array which then returns the maximum value in that array.

Similar to the person above, I used itertools, saving a lot of time calculating the combination of items. Dictionary is very helpful here.

# using combinations for this problem from itertools import * def knapsack(weight_cap, weights, values): # setting up dictionary, tying weights to its value dicty = {} for i in range(0, len(weights)): dicty[weights[i]] = values[i] keys = list(dicty.keys()) # find the number of unique ways the knapsack can carry without exceeding weight limit listofways = [] for j in range(1, len(keys)): verify = combinations(keys,j) for k in verify: if sum(k) > weight_cap: continue listofways.append(k) # finding the individual value from dictionary, from there find maximum value. value = 0 for l in listofways: testvalue = 0 for m in l: testvalue += dicty[m] if testvalue > value: value = testvalue return value weight_cap = 10 weights = [1, 3, 6, 8, 10] values = [950, 50, 60, 100, 1000] print(knapsack(weight_cap, weights, values))

Create list of combinations of weight indexes
Use those indexes to find total weight, remove any combos above the weight cap
Use indexes to find value
Return max value

from itertools import combinations def knapsack(weight_cap, weights, values): weight_indexes = [indx for indx,weight in enumerate(weights)] weight_index_combos = [] for l in range(1, len(weight_indexes) + 1): for subset in combinations(weight_indexes, l): weight_index_combos.append(subset) too_big = [] for subset in weight_index_combos: num = 0 for indx in subset: num += weights[indx] if num > weight_cap: too_big.append(subset) for subset in too_big: weight_index_combos.remove(subset) total_values = [] for subset in weight_index_combos: total_value = 0 for indx in subset: total_value += values[indx] total_values.append(total_value) return max(total_values)

A small summary of my code (I have used only Dynamic Programming to solve it):

Firstly we need to create and fill a matrix with the possible amounts that the bag can take according to the available gaps. I distinguish several cases:

  • Base cases:
    M[0,n] = 0 and M[n,0] = 0

  • M[k, w]
    Being w the total weight of the bag in a specific moment and wk the weight of an object.
    Being k the object.
    Being bk the value of the object.
    If wk > w → M[k-1, w]
    In another case → max (B[ k−1,w],B[ k−1,w−wk]+bk)

According to these we can fill the matrix.

After filling it, we loop through the matrix, starting from the bottom right, according to the next steps:

  • If M[k, w] == M[k-1, w]
    The object will not be selected and we passed to study the next one, in the row k-1.

  • If M[k, w] != M[k-1, w]
    The object will be selected, saving his value and studying the object in the same row, but w-wk colums, in the next iteration.

Once we arrive to the first column, which value is 0, we will have found our final and maximized solution.

def knapsack(weight_cap, weights, values): # Creation and filling of the matrix with the possible values according with the available gaps matrix = list() for row in range(0, len(weights)+1): new_row = list() for column in range(0, weight_cap+1): if row == 0 or column == 0: new_row.append(0) elif weights[row-1] > column: new_row.append(matrix[row-1][column]) else: new_row.append(max(matrix[row-1][column], values[row-1] + matrix[row-1][column-weights[row-1]])) matrix.append(new_row) for item in matrix: print(item) print() # Looping through the matrix by maximizing the total value of items curr_row = len(weights) next_row = curr_row - 1 curr_col = weight_cap curr_weight = len(weights)-1 quantity = 0 while curr_row != 0: if matrix[curr_row][curr_col] == matrix[next_row][curr_col]: curr_row = next_row next_row -= 1 curr_weight -= 1 else: curr_row -= 1 curr_col -= weights[curr_weight] quantity += values[curr_weight] curr_weight -= 1 next_row -= 1 return quantity weight_cap = 10 weights = [3, 6, 8] values = [50,60,100] print("Result:", knapsack(weight_cap, weights, values))