The Python Oracle

Returns True if the two strings only differ by one character

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 Returns True If The Two Strings Only Differ By One Character
00:33 Accepted Answer Score 13
01:46 Thank you

--

Full question
https://stackoverflow.com/questions/2866...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 13


Interesting question. A natural approach would be to use a full-fledged Levenshtein distance (AKA "edit distance") and ensure it equals 1. However, for the special case of 1, you can do better.

If the two strings are the same length, you clearly need to check that they differ in just one spot...:

if len(string1) == len(string2):
    count_diffs = 0
    for a, b in zip(string1, string2):
        if a!=b:
            if count_diffs: return False
            count_diffs += 1
    return True

If the length difference is above 1, then the result is clearly False.

The interesting case comes when the difference is exactly one -- in which case you must check if the longer string can be made into the shorter one by dropping exactly one character.

if abs(len(string1) - len(string2)) > 1: return False
if len(string1) < len(string2):
    string1, string2 = string2, string1

Here I'm swapping the strings, if needed, to ensure string1 is longer by exactly one character.

Now, we want to iterate independently on each string:

it1 = iter(string1)
it2 = iter(string2)
count_diffs = 0
c1 = next(it1, None)
c2 = next(it2, None)
while True:
    if c1 != c2:
        if count_diffs: return False
        count_diffs = 1
        c1 = next(it1)
    else:
        try:
            c1 = next(it1)
            c2 = next(it2)
        except StopIteration: return True

I'll leave it up to you how to put together these snippets to make the overall function work as intended -- so you can show at least some understanding of Python, as you're being asked to display!-)