- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to check whether there is any pair of words which are almost same in Python
Suppose we have a list of lowercase strings called words where each word is of same length. We have to check whether there are two strings that differ only in one character.
So, if the input is like words = ["seed", "pick", "lick", "root", "live"], then the output will be True, as "pick" and "lick" are almost same.
To solve this, we will follow these steps −
- s := a new set
- for each word in words, do
- for each index i and word w in word, do
- if substring of word[from index 0 to i - 1] concatenate "*" concatenate word[from index i + 1 to end] is present in s, then
- return True
- otherwise,
- insert (word[from index 0 to i-1] concatenate "*" concatenate word[from index i + 1 to end]) into s
- if substring of word[from index 0 to i - 1] concatenate "*" concatenate word[from index i + 1 to end] is present in s, then
- for each index i and word w in word, do
- return False
Example
Let us see the following implementation to get better understanding −
def solve(words): s = set() for word in words: for i, w in enumerate(word): if word[:i] + "*" + word[i + 1 :] in s: return True else: s.add(word[:i] + "*" + word[i + 1 :]) return False words = ["seed", "pick", "lick", "root", "live"] print(solve(words))
Input
["seed", "pick", "lick", "root", "live"]
Output
True
Advertisements