check if a pattern is in a list of words












0














I need an output that contains words that are exactly like a pattern - same letters in same spots only (and letters shouldn't show in the word at other places) and the same length
for example:



words = ['hatch','catch','match','chat','mates'] 
pattern = '_atc_


needed output:



['hatch','match']


I have tried to use nested for loops but it didn't work for a pattern that starts and ends with '_'



def filter_words_list(words, pattern):
relevant_words =
for word in words:
if len(word) == len(pattern):
for i in range(len(word)):
for j in range(len(pattern)):
if word[i] != pattern[i]:
break
if word[i] == pattern[i]:
relevant_words.append(word)


thx !










share|improve this question


















  • 1




    Just replace "_" with ".", then use your pattern as regular expression
    – quant
    Nov 11 at 13:20










  • what do you mean by replacing? the pattern is given
    – user10596917
    Nov 11 at 13:21










  • There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
    – quant
    Nov 11 at 13:24


















0














I need an output that contains words that are exactly like a pattern - same letters in same spots only (and letters shouldn't show in the word at other places) and the same length
for example:



words = ['hatch','catch','match','chat','mates'] 
pattern = '_atc_


needed output:



['hatch','match']


I have tried to use nested for loops but it didn't work for a pattern that starts and ends with '_'



def filter_words_list(words, pattern):
relevant_words =
for word in words:
if len(word) == len(pattern):
for i in range(len(word)):
for j in range(len(pattern)):
if word[i] != pattern[i]:
break
if word[i] == pattern[i]:
relevant_words.append(word)


thx !










share|improve this question


















  • 1




    Just replace "_" with ".", then use your pattern as regular expression
    – quant
    Nov 11 at 13:20










  • what do you mean by replacing? the pattern is given
    – user10596917
    Nov 11 at 13:21










  • There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
    – quant
    Nov 11 at 13:24
















0












0








0







I need an output that contains words that are exactly like a pattern - same letters in same spots only (and letters shouldn't show in the word at other places) and the same length
for example:



words = ['hatch','catch','match','chat','mates'] 
pattern = '_atc_


needed output:



['hatch','match']


I have tried to use nested for loops but it didn't work for a pattern that starts and ends with '_'



def filter_words_list(words, pattern):
relevant_words =
for word in words:
if len(word) == len(pattern):
for i in range(len(word)):
for j in range(len(pattern)):
if word[i] != pattern[i]:
break
if word[i] == pattern[i]:
relevant_words.append(word)


thx !










share|improve this question













I need an output that contains words that are exactly like a pattern - same letters in same spots only (and letters shouldn't show in the word at other places) and the same length
for example:



words = ['hatch','catch','match','chat','mates'] 
pattern = '_atc_


needed output:



['hatch','match']


I have tried to use nested for loops but it didn't work for a pattern that starts and ends with '_'



def filter_words_list(words, pattern):
relevant_words =
for word in words:
if len(word) == len(pattern):
for i in range(len(word)):
for j in range(len(pattern)):
if word[i] != pattern[i]:
break
if word[i] == pattern[i]:
relevant_words.append(word)


thx !







python list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 11 at 13:18







user10596917















  • 1




    Just replace "_" with ".", then use your pattern as regular expression
    – quant
    Nov 11 at 13:20










  • what do you mean by replacing? the pattern is given
    – user10596917
    Nov 11 at 13:21










  • There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
    – quant
    Nov 11 at 13:24
















  • 1




    Just replace "_" with ".", then use your pattern as regular expression
    – quant
    Nov 11 at 13:20










  • what do you mean by replacing? the pattern is given
    – user10596917
    Nov 11 at 13:21










  • There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
    – quant
    Nov 11 at 13:24










1




1




Just replace "_" with ".", then use your pattern as regular expression
– quant
Nov 11 at 13:20




Just replace "_" with ".", then use your pattern as regular expression
– quant
Nov 11 at 13:20












what do you mean by replacing? the pattern is given
– user10596917
Nov 11 at 13:21




what do you mean by replacing? the pattern is given
– user10596917
Nov 11 at 13:21












There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
– quant
Nov 11 at 13:24






There is a standard way of writing patterns in python. Your pattern however is using "_" - which is another syntax. So you simply need to convert your syntax to the standard syntax, then you can use the standard pattern matching library see docs.python.org/2/library/re.html ... as shown in the way of the answer from Daniel Masejo
– quant
Nov 11 at 13:24














2 Answers
2






active

oldest

votes


















1














So you should use regex. and replace the underscore with '.' which means any single character.
so the input looks like:



words = ['hatch','catch','match','chat','mates'] 
pattern = '.atc.'


and the code is:



import re
def filter_words_list(words, pattern):
ret =
for word in words:
if(re.match(pattern,word)):ret.append(word)
return ret


Hopes tha helped






share|improve this answer





























    1














    You could use a regular expression:



    import re

    words = ['hatch','catch','match','chat','mates']
    pattern = re.compile('[^atc]atc[^atc]')

    result = list(filter(pattern.fullmatch, words))
    print(result)


    Output



    ['hatch', 'match']


    The pattern '[^atc]atc[^atc]' matches everything that is not a or t or c ([^atc]) followed by 'atc' and again everything that is not a or t or c.



    As an alternative you could write your own matching function that will work with any given pattern:



    from collections import Counter


    def full_match(word, pattern='_atc_'):
    if len(pattern) != len(word):
    return False

    pattern_letter_counts = Counter(e for e in pattern if e != '_') # count characters that are not wild card
    word_letter_counts = Counter(word) # count letters

    if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
    return False

    return all(p == w for p, w in zip(pattern, word) if p != '_') # the word must match in all characters that are not wild card


    words = ['hatch', 'catch', 'match', 'chat', 'mates']


    result = list(filter(full_match, words))
    print(result)


    Output



    ['hatch', 'match']


    Further




    1. See the documentation on the built-in functions any and all.

    2. See the documentation on Counter.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249133%2fcheck-if-a-pattern-is-in-a-list-of-words%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown
























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      So you should use regex. and replace the underscore with '.' which means any single character.
      so the input looks like:



      words = ['hatch','catch','match','chat','mates'] 
      pattern = '.atc.'


      and the code is:



      import re
      def filter_words_list(words, pattern):
      ret =
      for word in words:
      if(re.match(pattern,word)):ret.append(word)
      return ret


      Hopes tha helped






      share|improve this answer


























        1














        So you should use regex. and replace the underscore with '.' which means any single character.
        so the input looks like:



        words = ['hatch','catch','match','chat','mates'] 
        pattern = '.atc.'


        and the code is:



        import re
        def filter_words_list(words, pattern):
        ret =
        for word in words:
        if(re.match(pattern,word)):ret.append(word)
        return ret


        Hopes tha helped






        share|improve this answer
























          1












          1








          1






          So you should use regex. and replace the underscore with '.' which means any single character.
          so the input looks like:



          words = ['hatch','catch','match','chat','mates'] 
          pattern = '.atc.'


          and the code is:



          import re
          def filter_words_list(words, pattern):
          ret =
          for word in words:
          if(re.match(pattern,word)):ret.append(word)
          return ret


          Hopes tha helped






          share|improve this answer












          So you should use regex. and replace the underscore with '.' which means any single character.
          so the input looks like:



          words = ['hatch','catch','match','chat','mates'] 
          pattern = '.atc.'


          and the code is:



          import re
          def filter_words_list(words, pattern):
          ret =
          for word in words:
          if(re.match(pattern,word)):ret.append(word)
          return ret


          Hopes tha helped







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 11 at 13:38









          Mbjahnoon

          212




          212

























              1














              You could use a regular expression:



              import re

              words = ['hatch','catch','match','chat','mates']
              pattern = re.compile('[^atc]atc[^atc]')

              result = list(filter(pattern.fullmatch, words))
              print(result)


              Output



              ['hatch', 'match']


              The pattern '[^atc]atc[^atc]' matches everything that is not a or t or c ([^atc]) followed by 'atc' and again everything that is not a or t or c.



              As an alternative you could write your own matching function that will work with any given pattern:



              from collections import Counter


              def full_match(word, pattern='_atc_'):
              if len(pattern) != len(word):
              return False

              pattern_letter_counts = Counter(e for e in pattern if e != '_') # count characters that are not wild card
              word_letter_counts = Counter(word) # count letters

              if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
              return False

              return all(p == w for p, w in zip(pattern, word) if p != '_') # the word must match in all characters that are not wild card


              words = ['hatch', 'catch', 'match', 'chat', 'mates']


              result = list(filter(full_match, words))
              print(result)


              Output



              ['hatch', 'match']


              Further




              1. See the documentation on the built-in functions any and all.

              2. See the documentation on Counter.






              share|improve this answer




























                1














                You could use a regular expression:



                import re

                words = ['hatch','catch','match','chat','mates']
                pattern = re.compile('[^atc]atc[^atc]')

                result = list(filter(pattern.fullmatch, words))
                print(result)


                Output



                ['hatch', 'match']


                The pattern '[^atc]atc[^atc]' matches everything that is not a or t or c ([^atc]) followed by 'atc' and again everything that is not a or t or c.



                As an alternative you could write your own matching function that will work with any given pattern:



                from collections import Counter


                def full_match(word, pattern='_atc_'):
                if len(pattern) != len(word):
                return False

                pattern_letter_counts = Counter(e for e in pattern if e != '_') # count characters that are not wild card
                word_letter_counts = Counter(word) # count letters

                if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
                return False

                return all(p == w for p, w in zip(pattern, word) if p != '_') # the word must match in all characters that are not wild card


                words = ['hatch', 'catch', 'match', 'chat', 'mates']


                result = list(filter(full_match, words))
                print(result)


                Output



                ['hatch', 'match']


                Further




                1. See the documentation on the built-in functions any and all.

                2. See the documentation on Counter.






                share|improve this answer


























                  1












                  1








                  1






                  You could use a regular expression:



                  import re

                  words = ['hatch','catch','match','chat','mates']
                  pattern = re.compile('[^atc]atc[^atc]')

                  result = list(filter(pattern.fullmatch, words))
                  print(result)


                  Output



                  ['hatch', 'match']


                  The pattern '[^atc]atc[^atc]' matches everything that is not a or t or c ([^atc]) followed by 'atc' and again everything that is not a or t or c.



                  As an alternative you could write your own matching function that will work with any given pattern:



                  from collections import Counter


                  def full_match(word, pattern='_atc_'):
                  if len(pattern) != len(word):
                  return False

                  pattern_letter_counts = Counter(e for e in pattern if e != '_') # count characters that are not wild card
                  word_letter_counts = Counter(word) # count letters

                  if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
                  return False

                  return all(p == w for p, w in zip(pattern, word) if p != '_') # the word must match in all characters that are not wild card


                  words = ['hatch', 'catch', 'match', 'chat', 'mates']


                  result = list(filter(full_match, words))
                  print(result)


                  Output



                  ['hatch', 'match']


                  Further




                  1. See the documentation on the built-in functions any and all.

                  2. See the documentation on Counter.






                  share|improve this answer














                  You could use a regular expression:



                  import re

                  words = ['hatch','catch','match','chat','mates']
                  pattern = re.compile('[^atc]atc[^atc]')

                  result = list(filter(pattern.fullmatch, words))
                  print(result)


                  Output



                  ['hatch', 'match']


                  The pattern '[^atc]atc[^atc]' matches everything that is not a or t or c ([^atc]) followed by 'atc' and again everything that is not a or t or c.



                  As an alternative you could write your own matching function that will work with any given pattern:



                  from collections import Counter


                  def full_match(word, pattern='_atc_'):
                  if len(pattern) != len(word):
                  return False

                  pattern_letter_counts = Counter(e for e in pattern if e != '_') # count characters that are not wild card
                  word_letter_counts = Counter(word) # count letters

                  if any(count != word_letter_counts.get(ch, 0) for ch, count in pattern_letter_counts.items()):
                  return False

                  return all(p == w for p, w in zip(pattern, word) if p != '_') # the word must match in all characters that are not wild card


                  words = ['hatch', 'catch', 'match', 'chat', 'mates']


                  result = list(filter(full_match, words))
                  print(result)


                  Output



                  ['hatch', 'match']


                  Further




                  1. See the documentation on the built-in functions any and all.

                  2. See the documentation on Counter.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 11 at 13:49

























                  answered Nov 11 at 13:23









                  Daniel Mesejo

                  12.5k1924




                  12.5k1924






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53249133%2fcheck-if-a-pattern-is-in-a-list-of-words%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Academy of Television Arts & Sciences

                      L'Équipe

                      1995 France bombings