ProgrammingVery hardCAT · MBA placement
What is printed?
What is printed?
def knap(items, cap):
dp = [0] * (cap + 1)
for w, v in items:
for c in range(cap, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[cap]
def knap_wrong(items, cap):
dp = [0] * (cap + 1)
for w, v in items:
for c in range(w, cap + 1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[cap]
items = [(2, 3), (3, 4), (4, 5)]
print(knap(items, 6), knap_wrong(items, 6))- A. 7 9
- B. 8 8
- C. 9 9
- D. 8 9
Correct answer: D. 8 9
The 0/1 version iterates capacity downward so each item is used at most once, giving 8 for capacity 6. The wrong version iterates upward, so an item can be reused, giving 2 + 2 + 2 = 9.
More Python Programming questions
- What is printed? python from collections import deque def knight(src, dst): seen = {src: 0} q = deque([src]) moves = [(1, 2), (2, 1), (-1…
- For an array of n = 10^5 values, which approach counts the distinct values in every window of size k = n / 2 in the least total time?
- What is printed? python a = [1, 2, 3, 4] try: print(a[len(a) / 2]) except TypeError: print('TypeError') print(a[len(a) // 2])
- What is printed? python s = 'u00b2' print(s.isdigit(), s.isdecimal(), s.isnumeric())
- What is printed? python d = {1: 'a'} d[1.0] = 'b' d[True] = 'c' print(d)
- What is printed? python def acc(): total = 0 while True: x = yield total if x is None: return total total += x g = acc() next(g) g.send(5)…