I am taking a Udemy course. The problem I am working on is to take two strings and determine if they are 'one edit away' from each other. That means you can make a single change -- change one letter, add one letter, delete one letter -- from one string and have it become identical to the other.
Examples:
s1a = "abcde"
s1b = "abfde"
s2a = "abcde"
s2b = "abde"
s3a = "xyz"
s3b = "xyaz"
s1a
changes the'c'
to an'f'
.s2a
deletes'c'
.s3a
adds'a'
.
The instructors solution (and test suite):
def is_one_away(s1, s2):
if len(s1) - len(s2) >= 2 or len(s2) - len(s1) >= 2:
return False
elif len(s1) == len(s2):
return is_one_away_same_length(s1, s2)
elif len(s1) > len(s2):
return is_one_away_diff_lengths(s1, s2)
else:
return is_one_away_diff_lengths(s2, s1)
def is_one_away_same_length(s1, s2):
count_diff = 0
for i in range(len(s1)):
if not s1[i] == s2[i]:
count_diff += 1
if count_diff > 1:
return False
return True
# Assumption: len(s1) == len(s2) + 1
def is_one_away_diff_lengths(s1, s2):
i = 0
count_diff = 0
while i < len(s2):
if s1[i + count_diff] == s2[i]:
i += 1
else:
count_diff += 1
if count_diff > 1:
return False
return True
# NOTE: The following input values will be used for testing your solution.
print(is_one_away("abcde", "abcd")) # should return True
print(is_one_away("abde", "abcde")) # should return True
print(is_one_away("a", "a")) # should return True
print(is_one_away("abcdef", "abqdef")) # should return True
print(is_one_away("abcdef", "abccef")) # should return True
print(is_one_away("abcdef", "abcde")) # should return True
print(is_one_away("aaa", "abc")) # should return False
print(is_one_away("abcde", "abc")) # should return False
print(is_one_away("abc", "abcde")) # should return False
print(is_one_away("abc", "bcc")) # should return False
When I saw the problem I decided to tackle it using set()
.
I found this very informative: Opposite of set.intersection in python?
This is my attempted solution:
def is_one_away(s1, s2):
if len(set(s1).symmetric_difference(s2)) <= 1:
return True
if len(set(s1).symmetric_difference(s2)) == 2:
if len(set(s1).difference(s2)) == len(set(s2).difference(s1)):
return True
return False
return False
When I run my solution online (you can test within the course itself) I am failing on the last test suite item:
False != True :
Input 1: abc
Input 2: bcc
Expected Result: False
Actual Result: True
I have tried and tried but I can't get the last test item to work (at least not without breaking a bunch of other stuff).
There is no guarantee that I can solve the full test suite with a set()
based solution, but since I am one item away I was really wanting to see if I could get it done.