ProgrammingVery hardCodeforces-style · placement coding round
What is printed?
What is printed?
def lcsub(a, b):
best = end = 0
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
if dp[i][j] > best:
best = dp[i][j]
end = i
return a[end - best:end]
print(lcsub('abcdxyz', 'xyzabcd'), lcsub('zxabcd', 'abcdzx'))- A. abcd abcd
- B. xyz abcd
- C. abcd zx
- D. abcd dcba
Correct answer: A. abcd abcd
The longest common substring is found by a DP table that tracks the run length ending at each pair of positions. Both pairs of strings share the substring abcd, which has length 4.
More Python Programming questions
- A solution must decide whether a number n up to 10^12 is prime within about one second in CPython. Which approach is correct and fast…
- What is printed? python d = {'a': 1, 'b': 2} print(d.popitem(), d)
- What is printed? python print('{0}{1}{0}'.format('x', 'y'))
- What is printed? python print(list(filter(None, [0, '', [], [0], None])))
- What is printed? python print([i for i in range(10) if i % 3 == 0][::-2])
- What is printed? python print(set('mississippi') == set('misp'), len(set('mississippi')))