
- 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
Program to check two strings are 0 or 1 edit distance away or not in Python
Suppose we have two strings S and T we have to check whether they are one or zero edit distance away or not. An edit operation can be defined as deleting a character, adding a character, or replacing a character with another character.
So, if the input is like S = "hello", T = "hallo", then the output will be True, as these two strings have edit distance of 1.
To solve this, we will follow these steps −
- m := size of S, n := size of T
- i := 0, j := 0
- count := 0
- if |m - n| > 1, then
- return False
- while i < m and j < n, do
- if S[i] is not same as T[j], then
- if count is same as 1, then
- return False
- if m < n, then
- j := j + 1
- otherwise when m > n, then
- i := i + 1
- otherwise,
- i := i + 1, j := j + 1
- count := count + 1
- if count is same as 1, then
- otherwise,
- i := i + 1, j := j + 1
- if S[i] is not same as T[j], then
- return True
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, S, T): m, n = len(S), len(T) i, j = 0, 0 count = 0 if abs(m - n) > 1: return False while i < m and j < n: if S[i] != T[j]: if count == 1: return False if m < n: j += 1 elif m > n: i += 1 else: i += 1 j += 1 count += 1 else: i += 1 j += 1 return True ob = Solution() S = "hello" T = "hallo" print(ob.solve(S, T))
Input
"hello", "hallo"
Output
True
- Related Articles
- C Program to check if two strings are same or not
- Java Program to check whether two Strings are an anagram or not.
- Check if edit distance between two strings is one in Python
- Program to check strings are rotation of each other or not in Python
- Check if two strings are equal or not in Arduino
- Check whether two strings are equivalent or not according to given condition in Python
- Program to check two strings can be equal by swapping characters or not in Python
- Program to check whether two sentences are similar or not in Python
- Program to check two rectangular overlaps or not in Python
- Program to check whether two string arrays are equivalent or not in Python
- How to check edit text values are Anagram or Not in android?
- Check if concatenation of two strings is balanced or not in Python
- Program to check whether final string can be formed using other two strings or not in Python
- Write a program in JavaScript to check if two strings are anagrams of each other or not
- Program to check two parts of a string are palindrome or not in Python

Advertisements