ProgrammingModerateAmazon OA · Flipkart coding round
What is printed?
What is printed?
def prod_except(a):
n = len(a)
out = [1] * n
left = 1
for i in range(n):
out[i] = left
left *= a[i]
right = 1
for i in range(n - 1, -1, -1):
out[i] *= right
right *= a[i]
return out
print(prod_except([1, 2, 3, 4]), prod_except([0, 5, 2]))- A. [24, 12, 8, 6] [10, 0, 0]
- B. [24, 12, 8, 6] [0, 0, 10]
- C. [24, 12, 8, 6] [10, 0, 1]
- D. [24, 12, 6, 8] [10, 0, 0]
Correct answer: A. [24, 12, 8, 6] [10, 0, 0]
A left-to-right pass stores the product of the earlier items, then a right-to-left pass multiplies in the product of the later items. A zero in the input forces zeros in the other positions.
More Python Programming questions
- What is printed? python import bisect def span(a, x): lo = bisect.bisectleft(a, x) if lo == len(a) or a[lo] != x: return (-1, -1) return…
- What is printed? python def palsub(s): n = len(s) best = '' for c in range(2 n - 1): l, r = c // 2, c // 2 + c % 2 while l >= 0 and r < n…
- What is printed? python def partition(s): last = {ch: i for i, ch in enumerate(s)} out = [] start = end = 0 for i, ch in enumerate(s): end…
- What is printed? python def units(boxes, cap): boxes = sorted(boxes, key=lambda b: -b[1]) total = 0 for n, u in boxes: take = min(n, cap)…
- What is printed? python def minremove(iv): iv = sorted(iv, key=lambda x: x[1]) keep = 0 end = float('-inf') for s, e in iv: if s >= end…
- What is printed? python def longest(s): st = [-1] best = 0 for i, ch in enumerate(s): if ch == '(': st.append(i) else: st.pop() if not st…