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

Coding challenges on optimization and the knapsack problem

Problem 1Optimization Models and the Knapsack Problem

Write the Plan for a Fractional Meal

The lecture's Food class and buildMenu are given in the starter code. Write the function fractional_plan(foods, maxCost) that solves the continuous version of the meal problem: you may eat any fraction of a food, and eating a fraction fff of a food with value vvv and ccc calories earns f⋅vf \cdot vf⋅v value and costs f⋅cf \cdot cf⋅c calories.

Assume foods is a list of Food objects with distinct names and positive calories, and maxCost is a non-negative number. Return a dict that maps the name of each food eaten in a positive amount to the fraction eaten (a float, 1.0 for the whole food), for a plan whose total value is as large as possible without exceeding maxCost calories. Foods that are not eaten at all must not appear in the dict. Do not modify foods.

names = ['wine', 'beer', 'pizza', 'burger', 'fries', 'cola', 'apple', 'donut']
values = [89, 90, 95, 100, 90, 79, 50, 10]
calories = [123, 154, 258, 354, 365, 150, 95, 195]
foods = buildMenu(names, values, calories)
plan = fractional_plan(foods, 750)
print(sorted(plan))              # ['apple', 'beer', 'cola', 'pizza', 'wine']
print(plan['wine'])              # 1.0
print(round(plan['pizza'], 4))   # 0.8837
print(fractional_plan(foods, 0)) # {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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 self.name + ': <' + str(self.value) + ', ' + str(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


def fractional_plan(foods, maxCost):
    """foods: a list of Food objects (distinct names, positive calories).
    maxCost: a non-negative calorie budget.
    Portions may be fractional, and a portion's value is proportional to
    the fraction eaten. Return a dict mapping the name of every food eaten
    (in a positive amount) to the fraction of it eaten, a float in (0, 1],
    for a plan of maximum total value. Do not modify foods."""
    pass

Scratchpad— run any Python to test ideas
1
2
3
4
5
# Scratchpad — run any Python here to test ideas.
# Anything you write below stays separate from the problem's tests.

print("hello, world")

Python runtime ready in a moment
Python runtime ready in a moment
Visible tests · 2Examples — click to expand
?
750-calorie plan on the lecture menu
?
a zero budget eats nothing
Hidden tests · 3Bodies hidden — pass/fail only
?
Hidden test 1
?
Hidden test 2
?
Hidden test 3