ProgrammingVery hardInfosys HackWithInfy · TCS CodeVita
What is printed?
What is printed?
import heapq
def medians(xs):
lo, hi = [], []
out = []
for x in xs:
heapq.heappush(lo, -x)
heapq.heappush(hi, -heapq.heappop(lo))
if len(hi) > len(lo):
heapq.heappush(lo, -heapq.heappop(hi))
out.append(-lo[0] if len(lo) > len(hi) else (-lo[0] + hi[0]) / 2)
return out
print(medians([5, 15, 1, 3]))- A. [5, 10, 5, 4]
- B. [5, 10.0, 5, 3.0]
- C. [5, 10.0, 5, 4]
- D. [5, 10.0, 5, 4.0]
Correct answer: D. [5, 10.0, 5, 4.0]
Two heaps keep the lower half in a max-heap and the upper half in a min-heap. Dividing by 2 in Python 3 gives a float, so the even-count medians print as 10.0 and 4.0.
More Python Programming questions
- What is printed? python def sieve(n): s = bytearray([1]) (n + 1) s[0:2] = bytes(2) for i in range(2, int(n 0.5) + 1): if s[i]: s[i i::i] =…
- What is printed? python a = [1, 2, 3] b = a b += [4] c = a + [5] a = a 2 print(b, c, a)
- What is printed? python def stepstocycle(f, s): seen = {} i = 0 while s not in seen: seen[s] = i s = f[s] i += 1 return i, i - seen[s]…
- What is printed? python from collections import Counter def divpairs(a, k): c = Counter(x % k for x in a) total = 0 for r in c: s = (k…
- What is printed? python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot('abcde', 'cdeab'), isrot('abc', 'acb')…
- What is printed? python def egcd(a, b): if b == 0: return a, 1, 0 g, x, y = egcd(b, a % b) return g, y, x - (a // b) y g, x, y = egcd(240…