Skip to content

Instantly share code, notes, and snippets.

@oskar456
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oskar456/39843d3282653f0064af to your computer and use it in GitHub Desktop.
Save oskar456/39843d3282653f0064af to your computer and use it in GitHub Desktop.
Find a word that consists of certian letters in dictionary (a.k.a. 4 Pics 1 Word helper)
#!/usr/bin/env python3
import argparse
import collections
import re
parser = argparse.ArgumentParser(
description='Find a word consisting of certain letters in dictionary'
)
parser.add_argument('letters',
help="letters to choose from"
)
parser.add_argument('-l', '--length',
help="length of the word",
type=int
)
parser.add_argument('-d', '--dictionary',
help="path to dictionary, default %(default)s",
default="/usr/share/dict/words"
)
parser.add_argument('-m', '--mask',
help="regular expression to mask found words, eg. '...e.s'"
)
args = parser.parse_args()
chars = collections.defaultdict(int)
for ch in args.letters.lower():
chars[ch] += 1
if args.mask:
mask = re.compile(args.mask, re.I)
with open(args.dictionary, 'r') as inf:
for word in (w.strip() for w in inf):
if ((args.length and len(word) != args.length) or
(args.mask and not mask.match(word))):
continue
my_chars = dict(chars)
for ch in word.lower():
if ch in my_chars and my_chars[ch]>0:
my_chars[ch] -= 1
else:
break
else:
print(word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment