ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
def edit(a, b):
    dp = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
    for i in range(len(a) + 1):
        for j in range(len(b) + 1):
            if i == 0 or j == 0:
                dp[i][j] = i + j
            elif a[i - 1] == b[j - 1]:
                dp[i][j] = dp[i - 1][j - 1]
            else:
                dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
    return dp[-1][-1]
print(edit('kitten', 'sitting'))
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 2

Correct answer: A. 3

kitten becomes sitting with two substitutions and one insertion, a total of 3 edits, which is the Levenshtein distance.

More Python Programming questions

Exams that ask this topic