ProgrammingHardTCS CodeVita · Infosys HackWithInfy
What is printed?
What is printed?
def lcs(a, b):
dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
for i in range(1, len(a) + 1):
for j in range(1, len(b) + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
return dp[-1][-1]
print(lcs('ABCBDAB', 'BDCABA'))- A. 3
- B. 5
- C. 4
- D. 2
Correct answer: C. 4
One longest common subsequence is BCBA, with length 4, so the bottom-right DP cell is 4. Where the characters differ, the cell takes the larger of its two neighbours.
More Python Programming questions
- What is printed? python items = [(60, 10), (100, 20), (120, 30)] cap = 50 best = 0 w = 0 for v, wt in sorted(items, key=lambda x: x[0] /…
- What is printed? python def mincapacity(w, days): lo, hi = max(w), sum(w) while lo < hi: mid = (lo + hi) // 2 need, cur = 1, 0 for x in w…
- What is printed? python from functools import lrucache @lrucache(maxsize=2) def sq(x): return x x for v in [1, 2, 1, 3, 1]: sq(v)…
- What is printed? python def nge(a): res = [-1] len(a) st = [] for i, x in enumerate(a): while st and a[st[-1]] < x: res[st.pop()] = x…
- What is printed? python def pickbystart(iv): iv = sorted(iv) cnt, end = 0, -109 for s, e in iv: if s >= end: cnt += 1 end = e return cnt…
- In CPython, which operation on a collections.deque is O(n) in the worst case?