Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Dynamic programming solution in Speedy category for String Conversion by Sim0000
def steps_to_convert(line1, line2):
"Dynamic programming"
n1, n2 = len(line1), len(line2)
if n1 == 0 or n2 == 0: return max(n1, n2)
d = [[0]*(n2 + 1) for _ in range(n1 + 1)]
for i in range(n1 + 1): d[i][0] = i
for i in range(n2 + 1): d[0][i] = i
for i in range(n1):
for j in range(n2):
f = line1[i] != line2[j]
d[i + 1][j + 1] = min(d[i + 1][j] + 1, d[i][j + 1] + 1, d[i][j] + f)
return d[n1][n2]
if __name__ == "__main__":
#These "asserts" using only for self-checking and not necessary for auto-testing
assert steps_to_convert('line1', 'line1') == 0, "eq"
assert steps_to_convert('line1', 'line2') == 1, "2"
assert steps_to_convert('line', 'line2') == 1, "none to 2"
assert steps_to_convert('ine', 'line2') == 2, "need two more"
assert steps_to_convert('line1', '1enil') == 4, "everything is opposite"
assert steps_to_convert('', '') == 0, "two empty"
assert steps_to_convert('l', '') == 1, "one side"
assert steps_to_convert('', 'l') == 1, "another side"
print("You are good to go!")
Oct. 5, 2016
Comments: