ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def cnt(xs, T):
xs = sorted(xs)
lo, hi, total = 0, len(xs) - 1, 0
while lo < hi:
if xs[lo] + xs[hi] <= T:
total += hi - lo
lo += 1
else:
hi -= 1
return total
print(cnt([1, 2, 3, 4], 5))- A. 4
- B. 3
- C. 5
- D. 6
Correct answer: A. 4
Two-pointer count of pairs with sum at most T. Whenever xs[lo] + xs[hi] <= T, every index between lo and hi-1 also pairs with hi, so hi - lo pairs are counted. The pairs with sum <= 5 are (1,2), (1,3), (1,4), (2,3), so the answer is the count of those, 4.
More Python Programming questions
- What is printed? python 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]…
- 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] +…