ProgrammingVery hardCAT · MBA placement
What is printed?
What is printed?
def greedy(coins, amt):
cnt = 0
for c in sorted(coins, reverse=True):
cnt += amt // c
amt %= c
return cnt if amt == 0 else -1
print(greedy([1, 3, 4], 6))- A. 3
- B. 2
- C. 4
- D. -1
Correct answer: A. 3
Largest-first greedy takes 4, then 1 and 1, which is 3 coins. The optimal answer is 3 + 3, which uses only 2 coins, so greedy is not safe for arbitrary coin sets.
More Python Programming questions
- What is printed? python import bisect def lis(a): t = [] for x in a: i = bisect.bisectleft(t, x) if i == len(t): t.append(x) else: t[i] =…
- A list a is sorted in ascending order and may contain duplicates. Using bisectleft and bisectright from the bisect module, which…
- A Python list q holds n items. A loop repeatedly does x = q.pop(0) until q is empty. What is the total time cost of the loop in big-O terms?
- What is printed? python def rob(a): p, c = 0, 0 for x in a: p, c = c, max(c, p + x) return c print(rob([2, 7, 9, 3, 1]), rob([5]), rob([]))
- What is printed? python def ed(a, b): prev = list(range(len(b) + 1)) for i in range(1, len(a) + 1): cur = [i] + [0] len(b) for j in…
- What is printed? python def minlen(a, t): best = float('inf') s = 0 l = 0 for r, x in enumerate(a): s += x while s >= t: best = min(best…