ProgrammingVery hardCAT · MBA placement
What is printed?
What is printed?
items = [(60, 10), (100, 20), (120, 30)]
cap = 50
best = 0
w = 0
for v, wt in sorted(items, key=lambda x: x[0] / x[1], reverse=True):
if w + wt <= cap:
w += wt
best += v
print(best)- A. 220
- B. 180
- C. 240
- D. 160
Correct answer: D. 160
Greedy by value per weight takes the 60 and 100 items, which weigh 30. The 120 item then does not fit in the remaining 20, so the total is 160; the optimal pair 100 and 120 gives 220.
More Python Programming questions
- What is printed? python def mincapacity(w, days): lo, hi = max(w), sum(w) while lo < hi: mid = (lo + hi) // 2 need, cur = 1, 0 for x in w…
- What is printed? python from functools import lrucache @lrucache(maxsize=2) def sq(x): return x x for v in [1, 2, 1, 3, 1]: sq(v)…
- What is printed? python def nge(a): res = [-1] len(a) st = [] for i, x in enumerate(a): while st and a[st[-1]] < x: res[st.pop()] = x…
- What is printed? python def pickbystart(iv): iv = sorted(iv) cnt, end = 0, -109 for s, e in iv: if s >= end: cnt += 1 end = e return cnt…
- In CPython, which operation on a collections.deque is O(n) in the worst case?
- What is printed? python def primes(n): s = [True] (n + 1) s[0:2] = [False, False] for i in range(2, int(n 0.5) + 1): if s[i]: s[i i::i] =…