-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtools.py
138 lines (85 loc) · 2.87 KB
/
tools.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def loadWords():
"""
txt: a string, 'words.txt';
returns a list containing all the words.
"""
filename = 'words.txt'
print('Loading words from', filename)
fh = open(filename, 'r')
words = []
for word in fh:
word = word.strip().lower()
words.append(word)
print(' {} words loaded'.format(len(words)))
print('PlayGame not yet implemented')
return words
def getFreqDict(string):
"""
string: a string of letters as input.
returns a dictionary with the frequency of each letter.
"""
d = {}
for i in string:
i = i.lower()
d[i] = d.get(i, 0) + 1
return d
def dealHand():
"""
returns n lowercase letters
"""
import random
import string
vowels = 'aeiou'
constant = 'bcdfghjklmnpqrstvwxyz'
maxint = max(list(map(len, wordlist)))
n = random.randint(5, maxint)
# 1/3 vowls
n_vowl = n // 3
n_constant = n - n//3
get_vowl = random.choices(vowels, k = n_vowl)
get_constant = random.choices(constant, k = n_constant)
strings = ''.join(get_vowl + get_constant)
hand = getFreqDict(strings)
return hand
def displayHand(hand):
"""
d: a dictionary containing delt hand;
returns a string in your hand
"""
display = ''
for k in hand.keys():
display = display + ' '.join(list(k * hand[k])) + ' ' # o mm z g j
return display
def updateHand(hand, word):
"""
hand: a dictionary, the letters in your hand
word: the word you used, assume it is valid
returns updated dictionary containing the frequency of the remaining letters
"""
#new_hand = dict()
hand_copy = hand.copy()
for i in word:
if i in hand.keys():
hand_copy[i] = hand_copy.get(i, 0) - 1 # get(i, default) if i in the key, return the d[i] value
# if i is not in the key, then return 0
return hand_copy
def isValidWord(word, hand, wordlist):
"""
word: a string, the word you come up with from the hand
hand: a dictionary, containing the letters you have got
wordlist: a list, the provided wordlist
returns: a boolean, True if the word is valid in the word list
False if the word is not in the word list.
"""
hand_copy = hand.copy()
word_copy = wordlist.copy()
word_set = set(word_copy)
your_word = getFreqDict(word)
if word not in word_set:
return False
else:
for k in your_word.keys():
if (k not in hand_copy.keys()) or (your_word[k] > hand_copy[k]):
return False
else:
return True