0

I am trying to print only words that match the regex I provide and only contain the letters provided in the second parameter. The regex works perfectly, but the letter selection does not.

import re

def search(regex,letters):
    letters=set(letters)
    pattern=re.compile(regex)
    for word in content:
        word=word.strip()
        if(pattern.findall(word)):
            if letters & set(word):
                print(word)


#search(r'^(n|u|p|g|o|u|e|b|l){6}$')
#search(r'^t(i|a)[a-z]{3}')
content=["hello","helps","halts","random"]
search(r'^h(e|a)[a-z]{3}','hltsa') #returns: hello,helps,halts

My goal is to get this to return only halts, because it matches the second parameter.

Rilcon42
  • 9,584
  • 18
  • 83
  • 167

1 Answers1

0
import re

def search(regex,letters):
    letters=set(letters)
    pattern=re.compile(regex)
    for word in content:
        word=word.strip()
        if(pattern.findall(word)):
            if set(word) >= letters:
                print(word)


#search(r'^(n|u|p|g|o|u|e|b|l){6}$')
#search(r'^t(i|a)[a-z]{3}')
content=["hello","helps","halts","random"]
search(r'^h(e|a)[a-z]{3}','hltsa') #returns: hello,helps,halts

try this, I only changed if letters & set(word):

in documentation for sets you can find this

s.issubset(t)    s <= t  test whether every element in s is in t
s.issuperset(t)  s >= t  test whether every element in t is in s
Aleksander Monk
  • 2,787
  • 2
  • 18
  • 31