[Solved] Check if n is in array [closed]


If I was developing this, I would:

  • Keep all the words in a single set
  • Skip the first question (you can determine word length by the length of the 2nd question)
  • Set up a while loop for each question you ask the user so that it repeats the same question on invalid input.

To check for the word, you could compile a regular expression and replace all _‘s with .s:

regex = re.compile(guess.replace('_', '.') + '$')

Now the part you’ve been waiting for, checking if an item in the set matches:

match = [m.group(0) for word in wordlist for m in [regex.match(word)] if m]
print(' '.join(match) or "No matches")

The list comprehension above basically iterates through every word in the list (which can be prefiltered by length if you prefer), then checks it to see if it matches the regular expression created earlier. If it’s a match, m will be a Match Object that you can get the first group of which will be the word you are looking for all packaged together as a list of words that match.

The last line prints all the matches separated by a space, or “No matches” if there isn’t any matches.

This code is untested, and I’m not familiar with Python 3 as I am with Python 2. Good luck!

7

solved Check if n is in array [closed]