Complete the code to select the next best item greedily based on value.
items = [(60, 10), (100, 20), (120, 30)] # (value, weight) items.sort(key=lambda x: x[[1]], reverse=True) print(items)
We sort items by their value (index 0) in descending order to pick the highest value first.
Complete the code to calculate the value-to-weight ratio for greedy selection.
items = [(60, 10), (100, 20), (120, 30)] ratios = [item[0] / item[[1]] for item in items] print(ratios)
Weight is at index 1, so dividing value by weight gives the ratio.
Fix the error in the greedy coin change algorithm to pick the largest coin first.
coins = [1, 5, 10, 25] coins.sort(reverse=[1]) change = 63 result = [] for coin in coins: while change >= coin: change -= coin result.append(coin) print(result)
Sorting coins in descending order (reverse=True) ensures greedy picks largest coin first.
Fill both blanks to create a dictionary comprehension that maps words to their lengths only if length > 3.
words = ['apple', 'bat', 'car', 'door'] lengths = {word: [1] for word in words if len(word) [2] 3} print(lengths)
We map each word to its length (len(word)) only if length is greater than 3.
Fill all three blanks to create a dictionary comprehension filtering items with positive values and keys uppercased.
data = {'a': 1, 'b': -2, 'c': 3}
result = { [1]: [2] for k, v in data.items() if v [3] 0 }
print(result)Keys are uppercased (k.upper()), values kept as v, filtered where value > 0.
