![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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 find out if the strings supplied differ by a character in the same position in Python
Suppose, we are provided an array that contains several strings that are of the same length. We have to find out if any two of the supplied strings differ by a single character at the same position. If this difference is present, we return true or else we return false.
So, if the input is like dict = ['pqrs', 'prqs', 'paqs'], then the output will be True. The output produced is True because the strings listed in the input all differ in index 1. So, if any two pairs are taken, there is a difference in the same position.
To solve this, we will follow these steps −
seens := a new set
for each word in dict, do
for each index i and character c in word, do
masked_word := word[from index 0 to i] + '.' + word[from index i+1 to end of string]
if masked_word is present in seens, then
return True
otherwise,
add(masked_word) to seens
return False
Example (Python)
Let us see the following implementation to get better understanding −
def solve(dict): seens = set() for word in dict: for i, c in enumerate(word): masked_word = word[:i] + '.' + word[i+1:] if masked_word in seens: return True else: seens.add(masked_word) return False print(solve(['pqrs', 'prqs', 'paqs']))
Input
['pqrs', 'prqs', 'paqs']
Output
True