ProgrammingHardAmazon OA · Flipkart coding round
What is printed?
What is printed?
def closest3(a, t):
a = sorted(a)
best = None
for i in range(len(a) - 2):
l, r = i + 1, len(a) - 1
while l < r:
s = a[i] + a[l] + a[r]
if best is None or abs(s - t) < abs(best - t):
best = s
if s < t:
l += 1
elif s > t:
r -= 1
else:
return s
return best
print(closest3([-1, 2, 1, -4], 1), closest3([0, 0, 0], 1))- A. 1 0
- B. 2 1
- C. 2 0
- D. 3 0
Correct answer: C. 2 0
Sorting and two pointers track the sum nearest to the target. For [-1, 2, 1, -4] the best sum is 2, and [0, 0, 0] can only give 0.
More Python Programming questions
- What is printed? python print(0.0 == -0.0, -0.0, 1e16 + 1 == 1e16, 2 53 + 1 == 2 53)
- What is printed? python import bisect xs = [1, 4, 4, 9] i = bisect.bisectleft(xs, 4) xs.insert(i, 4) print(xs, bisect.bisectright(xs, 4)…
- What is printed? python from collections import deque d = deque(range(5)) d.rotate(-2) print(list(d), d[0], d[-1])
- What is printed? python import heapq h = [] for x in [5, 1, 3]: heapq.heappush(h, x) heapq.heappush(h, 0) print([heapq.heappop(h) for in…
- What is printed? python s = 'hello' print(s.index('l'), s.rfind('l'), s.find('l', 3), s.index('lo'))
- What is printed? python import itertools print(sum(1 for in itertools.combinations(range(6), 2)), sum(1 for in…