Lecture 18 Finger Exercise
Please Log In for full access to the web site.
Note that this link will take you to an external site (https://shimmer.mit.edu) to authenticate, and then you will be redirected back to this page.
Suppose we are given a scenario where the weights and capacity represent money in dollars and cents, i.e., the weights are prices, and the capacity is a budget.
Write a function You may assume the inputs are in the same format as for knapsack_indexed_tabular() function:
Click to see the code for
knapsack_indexed_tabular()def knapsack_indexed_tabular(items, capacity):
# initialize table
n = len(items)
table = [
[ ([], 0) for _ in range(capacity + 1) ]
for _ in range(n + 1)
]
# fill in table from bottom row
for i in range(n - 1, -1, -1):
name, value, weight = items[i]
for cap in range(capacity + 1):
sol_without, val_without = table[i + 1][cap]
if weight < cap:
sol_with, val_with = table[i + 1][cap - weight]
sol_with = sol_with + [name]
val_with += value
else:
sol_with = []
val_with = 0
if val_with > val_without:
table[i][cap] = sol_with, val_with
else:
table[i][cap] = sol_without, val_without
# retrieve answer for original problem
return table[0][capacity]
knapsack_with_prices(items, capacity) that solves such scenarios.
Like the original code, it should return an items, value tuple that is expresses an optimal subset of items and its total value.knapsack_indexed_tabular(), except that monetary values are given as floats with two decimal places.
You may also assume the original knapsack_indexed_tabular() function is defined and available to you.
Question 2.
You are presented a row of apples and oranges, and you would like to select a heaviest set of apples, with none being adjacent to each other. The submission box below is pre-populated with code that correctly solves this problem, but it takes a long time on larger input lists.
Memoize the code so that it runs correctly under one-tenth of a second for each test case. You may expand the following line to reference the original code:Click to see the original code for
choose_apples()def choose_apples_helper(lineup, index):
if index >= len(lineup):
return [], 0
fruit, weight = lineup[index]
if fruit != "apple":
return choose_apples_helper(lineup, index + 1)
sol_without, weight_without = choose_apples_helper(lineup, index + 1)
sol_with, weight_with = choose_apples_helper(lineup, index + 2)
sol_with = [index] + sol_with
weight_with += weight
if weight_without > weight_with:
return sol_without, weight_without
else:
return sol_with, weight_with
def choose_apples(lineup):
"""
lineup is a list of tuples, each of the form ("apple", weight) or
("orange", weight), where weight is a positive float.
Return a list of non-adjacent indicies into lineup, such that the
tuples at those indicies all represent "apple"s, and their total
weight is maximized.
"""
return choose_apples_helper(lineup, 0)[0]