ProgrammingHardTCS CodeVita · Infosys HackWithInfy
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]
print(knap([(2, 3), (3, 4), (4, 5)], 5), knap([(1, 1)], 0))- A. 8 0
- B. 7 0
- C. 7 1
- D. 5 0
Correct answer: B. 7 0
The inner loop runs downward so each item is used at most once. With capacity 5, the best choice is items of weight 2 and 3, with value 7. A capacity of 0 can take nothing.
More Python Programming questions
- What is printed? python import heapq h = [] for x in [4, 9, 1, 7]: heapq.heappush(h, -x) print(-heapq.heappop(h), -h[0])
- What is printed? python from functools import partial def power(base, exp): return base exp sq = partial(power, exp=2) cubeofthree =…
- What is printed? python import itertools it = itertools.count(10, 5) print(list(itertools.islice(it, 3)), next(it))
- What is printed? python words = ['b', 'a', 'c'] pairs = list(zip(sorted(words), range(10, 13))) print(pairs, dict(pairs)['c']…
- What is printed? python s = 'aabbbc' out = [] i = 0 while i < len(s): j = i while j < len(s) and s[j] == s[i]: j += 1 out.append(s[i] +…
- What is printed? python import math print(math.comb(10, 3) % 7, math.perm(5, 2), math.factorial(5) // math.factorial(3))