-
Notifications
You must be signed in to change notification settings - Fork 0
/
solveWordPuzzle.py
63 lines (56 loc) · 1.99 KB
/
solveWordPuzzle.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import pprint
import pydash
import enchant
import sys
def solvePuzzle(string, numLetters=None, startsWith=None, contains=None):
"""
1. Get the permutations of the string
2. group them by the length of the string
2.5 check them against an api to determine valid words
3. pretty print
"""
string = string.lower()
if numLetters:
numLettrs = int(numLetters)
permutations = getPermutations(string)
WordCheck = enchant.Dict("en_US")
filtered = list(filter(lambda perm: len(perm) >= 3 and WordCheck.check(perm), permutations))
permsByLen = pydash.collections.group_by(filtered, lambda x: len(x))
if numLetters:
permsByLen = permsByLen[numLetters]
if startsWith:
permsByLen = list(filter(lambda x: x[0] == startsWith, permsByLen))
if contains:
for char in contains:
permsByLen = list(filter(lambda x: char in x, permsByLen))
pprint.pprint(permsByLen)
def getPermutations(string):
permutations = set()
stringDict = {}
for char in string:
if char in stringDict:
stringDict[char] += 1
else:
stringDict[char] = 0
permutationHelper(string, "", permutations, stringDict)
return permutations
def permutationHelper(string, perm, permutations, stringDict):
if not string:
return
permutations.add(perm)
permStringDict = {}
for char in perm:
if char in permStringDict:
permStringDict[char] += 1
else:
permStringDict[char] = 0
for index in range(len(string)):
if string[index] in permStringDict and permStringDict[string[index]] + 1 > stringDict[string[index]]:
continue
perm += string[index]
permutationHelper(string, perm, permutations, stringDict)
perm = perm[0:len(perm) - 1]
if __name__== "__main__":
while len(sys.argv) < 5:
sys.argv.append("")
solvePuzzle(str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]), str(sys.argv[4]))