ProgrammingVery hardCognizant GenC · TCS NQT
What is printed?
What is printed?
def longest(s):
st = [-1]
best = 0
for i, ch in enumerate(s):
if ch == '(':
st.append(i)
else:
st.pop()
if not st:
st.append(i)
else:
best = max(best, i - st[-1])
return best
print(longest(')()())'), longest('(()'))- A. 2 2
- B. 4 1
- C. 4 2
- D. 6 2
Correct answer: C. 4 2
A stack of indices marks where the current valid run starts. The longest valid run in )()()) is ()() with length 4, and (() contains the valid pair () of length 2.
More Python Programming questions
- What is printed? python import heapq from collections import Counter words = 'a b c a b a d d d d'.split() c = Counter(words)…
- What is printed? python from functools import cache @cache def cat(n): if n <= 1: return 1 return sum(cat(i) cat(n - 1 - i) for i in…
- What is printed? python from functools import lrucache grid = [[1, 3, 1], [1, 5, 1], [4, 2, 1]] @lrucache(maxsize=None) def best(r, c): if…
- What is printed? python def sigma(n): return sum(d for d in range(1, n + 1) if n % d == 0) perfect = [n for n in range(2, 30) if sigma(n)…
- What is printed? python def phi(n): res, p = n, 2 while p p <= n: if n % p == 0: while n % p == 0: n //= p res -= res // p p += 1 if n >…
- What is printed? python def cntinc(a, k): dp = [[0] (k + 1) for in range(len(a))] for i in range(len(a)): dp[i][1] = 1 for j in range(i)…