Find and Replace Pattern in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of words and a pattern, and we have to find which words in words matches the pattern. Here a word matches the pattern if there exists a permutation of letters p so that after replacing every letter x in the pattern with p(x), we get the target word. We have to find a list of the words in words that match the given pattern.

So for example, if the input is like ["abc","deq","mee","aqq","dkd","ccc"] and pattern is “abb”, then the output will be [“mee”, “aqq”], here mee and aqq are matching the style of the pattern “abb”. but “ccc” is not a pattern, because this is not a permutation.

To solve this, we will follow these steps −

  • define one convert() method. This will take word as input, this will act like −
  • counter := 1, s := empty string
  • s := s + string equivalent of counter
  • for i in range 1 to length of word – 1
    • j := i – 1
    • while j>=0
      • if word[j] is word[i], then break
      • decrease j by 1
    • if j > -1, then s := s + s[j], otherwise increase counter by 1 and s := s + counter value as string
  • return s
  • the actual method will be like
  • make one array word_num, and this is empty, make another empty array res
  • for each element i in words −
    • insert convert(i) into word_num
  • pattern := convert(pattern)
  • for i in range 0 to length of words – 1
    • if words_num[i] = pattern, then insert words[i] into res
  • return res

Let us see the following implementation to get better understanding −


 Live Demo

class Solution(object):
   def findAndReplacePattern(self, words, pattern):
      words_num = []
      result = []
      for i in words:
      pattern = self.convert(pattern)
      for i in range(len(words)):
         if words_num[i] == pattern:
      return result
   def convert(self,word):
      counter = 1
      s = ""
      for i in range(1,len(word)):
         j= i -1
         while j>=0:
            if word[j] == word[i]:
         if j >-1:
      return s
ob = Solution()




['mee', 'aqq']
Published on 30-Apr-2020 06:17:52