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)
        break
  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:
                continue
        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:
          tots.append(values[i3])
          #print(values[i3], " \t", amount)
        
    else:
      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]
              
          else:
            total_weight+= weights[c2];
            total_value+= values[c2]
          #print(total_value, "\t", amount)
          #print("\t",total_weight)
          if total_weight <= weight_cap:
            tots.append(total_value)
  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
            weight_value_dict[w].append(v)
        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:
                break
        else:
            weight_combination.append(_)
    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]
                b.sort()
                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))
powersetweights.remove()

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])):
valuelist.append(values[weights.index(powersetweights[i][j])])
Totals.append(sum(valuelist))
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])
            else:
                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