Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Second solution in Clear category for String Conversion by Sim0000
from collections import deque
def steps_to_convert(line1, line2):
"BFS version"
q = deque([(line1, line2, 0)])
while q:
s1, s2, n = q.popleft()
if s1 == s2 == '': return n
if s1 and s2 and s1[0] == s2[0]:
# When first characters are same, skip it ('line', 'line') -> ('ine', 'ine')
q.appendleft((s1[1:], s2[1:], n))
else:
# Delete ('aline', 'line') -> ('line', 'line') ... remove 'a'
if s1: q.append((s1[1:], s2, n + 1))
# Insert ('ine', 'line') -> ('line', 'line') ... prepend 'l'
if s2: q.append((s2[0] + s1, s2, n + 1))
# Replace ('xine', 'line') -> ('line', 'line') ... replace 'x' with 'l'
if s1 and s2: q.append((s2[0] + s1[1:], s2, n + 1))
raise Exception('never reach')
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