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

Optimization Models and the Knapsack Problem

What turns a choice into an optimization problem, and why is the knapsack easy with gold dust but hard with gold bars?


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

Constraints rule trips in or out

You are travelling from New York to Boston. Each trip in trips has its travel time in minutes, its cost in dollars, and its arrival time as an hour of the day (16.5 is 4:30 PM). A trip is allowed only if it costs at most budget and arrives strictly before deadline. Build the list of the allowed trips' mode names, in the order they appear in trips, and assign it to feasible.

1
2
3
4
5
6
7
8
9
10
11
12
13
trips = [
    {"mode": "plane", "minutes": 75, "cost": 250, "arrive": 13.0},
    {"mode": "bus", "minutes": 270, "cost": 15, "arrive": 17.5},
    {"mode": "car", "minutes": 240, "cost": 40, "arrive": 16.5},
    {"mode": "train", "minutes": 225, "cost": 95, "arrive": 16.0},
]
budget = 100
deadline = 17.0  # 5:00 PM, as an hour of the day

# Keep only the modes of the trips that honor both constraints.
feasible = ...  # your code here

Python runs in your browser
⌘/Ctrl + Enter runs
?
is a list
?
drops the trip that is over budget
?
drops the trip that arrives too late
?
keeps exactly the allowed modes, in table order
Next Brute-Force Knapsack and the Exponential Power Set →