
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Check if edit distance between two strings is one in Python
Suppose we have two strings s and t. We have to check whether the edit distance between s and t is exactly one or not. Here edit between two strings means any of these three −
- Insert a character
- Delete a character
- Replace a character
So, if the input is like s = "hello" t = "heillo", then the output will be True as we need to insert one character into s to get t.
To solve this, we will follow these steps −
- if |size of s - size of t| > 1, then
- return false
- edit_dist_cnt := 0, i := 0, j := 0
- while i < size of s and j < size of t, do
- if s[i] is not same as t[j], then
- if edit_dist_cnt is same as 1, then
- return false
- if size of s > size of t, then
- i := i + 1
- otherwise when size of s < size of t, then
- j := j + 1
- otherwise,
- i := i + 1, j := j + 1
- edit_dist_cnt := edit_dist_cnt + 1
- if edit_dist_cnt is same as 1, then
- otherwise,
- i := i + 1, j := j + 1
- if s[i] is not same as t[j], then
- if i < size of s or j < size of t, then
- edit_dist_cnt := edit_dist_cnt + 1
- return true when edit_dist_cnt is same as 1, otherwise false
Example
Let us see the following implementation to get better understanding −
def solve(s, t): if abs(len(s) - len(t)) > 1: return false edit_dist_cnt = 0 i = 0 j = 0 while i < len(s) and j < len(t): if s[i] != t[j]: if edit_dist_cnt == 1: return false if len(s) > len(t): i += 1 elif len(s) < len(t): j += 1 else: i += 1 j += 1 edit_dist_cnt +=1 else: i += 1 j += 1 if i < len(s) or j < len(t): edit_dist_cnt += 1 return edit_dist_cnt == 1 s = "hello" t = "heillo" print(solve(s, t))
Input
"hello", "heillo"
Output
True
- Related Articles
- Program to check two strings are 0 or 1 edit distance away or not in Python
- Program to find the minimum edit distance between two strings in C++
- One Edit Distance in C++
- Python - Check if two strings are isomorphic in nature
- Hamming Distance between two strings in JavaScript
- Check if concatenation of two strings is balanced or not in Python
- How to check if one date is between two dates in JavaScript?
- Meta Strings (Check if two strings can become same after a swap in one string) in C++
- Edit Distance in C++
- How to check similarity between two strings in MySQL?
- Edit Distance\n
- Program to check is there any permutation that is lexicographically bigger or not between two strings in Python
- How to check if two strings are equal in Java?
- Check if two strings are equal or not in Arduino
- Smallest Distance Between Two Words in Python

Advertisements