Ludium
Sign In
Introduction to Computational Thinking and Data Science
Optimization
01Optimization Models and the Knapsack Problem02Brute-Force Knapsack and the Exponential Power Set03Greedy Algorithms: One Function, Any Definition of Best04Lambda Keys and Why Greedy Can Miss the OptimumProblem set0/10MIT problem set0/2
01The Knapsack Search Tree: Every Combination, 2ⁿ Nodes02Recursive maxVal: An Exhaustive Search That Beats Greedy03Memoization: Turning Slow Fibonacci into fastFib04Overlapping Subproblems and the Memoized KnapsackProblem set0/10MIT problem set0/2

Recursive maxVal: An Exhaustive Search That Beats Greedy

How does a short recursive maxVal search the whole knapsack tree without ever building it, and where does it hit an exponential wall?


Finger exercises

Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.

0 / 5 passed
Exercise 1 of 5

How many branches does a node explore

Each call of maxVal(toConsider, avail) is one node of the search tree, and it makes either 0, 1 or 2 recursive calls: none when there is nothing left to decide or no room left, one when the first item cannot fit, two when it can. Items are Food objects (the class is given), so an item's weight is getCost(). Define branchesToExplore(toConsider, avail) that returns how many recursive calls that node makes.

Given code — runs before yours
class Food(object):
    def __init__(self, n, v, w):
        self.name = n
        self.value = v
        self.calories = w

    def getValue(self):
        return self.value

    def getCost(self):
        return self.calories

    def density(self):
        return self.getValue()/self.getCost()

    def __str__(self):
        return f'{self.name}: <{self.value}, {self.calories}>'

def buildMenu(names, values, calories):
    menu = []
    for i in range(len(values)):
        menu.append(Food(names[i], values[i], calories[i]))
    return menu
1
2
3
4
5
def branchesToExplore(toConsider, avail):
    # Return 0, 1 or 2: how many recursive calls maxVal makes at this node.
    return ...  # your code here

Python runs in your browser
⌘/Ctrl + Enter runs
?
returns an int
?
base case: nothing left, or no room left
?
a first item that cannot fit prunes the take branch
?
a first item that fits explores both branches
←Previous The Knapsack Search Tree: Every Combination, 2ⁿ NodesNext Memoization: Turning Slow Fibonacci into fastFib →