Hackbright Code Challenges

One Edit Away?

One Edit Away?

Challenge

Medium

Concepts

Strings, Logic

Download

one-away.zip

Solution

One Edit Away?: Solution


We want to check if two strings are, at most, one edit away from being the same. An edit is adding, deleting, or changing a single letter.

So, for example, “make” can be turned into “fake” by just changing one letter:

>>> one_away("make", "fake")
True

But we can’t turn “task” into “take” without changing two letters:

>>> one_away("task", "take")
False

We can turn “ask” into “asks” by adding a single letter:

>>> one_away("ask", "asks")
True

And we can turn “asks” into “ask” by removing a single letter:

>>> one_away("asks", "ask")
True

We’ve given you a file, oneaway.py, with a stub of a function in it:

def one_away(w1, w2):
    """Given two strings, are they, at most, one edit away?"""

Complete this function.

Think about the problem before you start writing — it’s easy to solve this in an inefficient, brute-force way with very poor runtime. Do some work with paper and pencil on some edits to figure out some patterns about how you could check these words without having to try every possible edit or try every possible letter insertion.