forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
guess-the-word.py
68 lines (60 loc) · 2.22 KB
/
guess-the-word.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
# Time: O(n^2)
# Space: O(n)
import collections
import itertools
class Solution(object):
def findSecretWord(self, wordlist, master):
"""
:type wordlist: List[Str]
:type master: Master
:rtype: None
"""
def solve(H, possible):
min_max_group, best_guess = possible, None
for guess in possible:
groups = [[] for _ in xrange(7)]
for j in possible:
if j != guess:
groups[H[guess][j]].append(j)
max_group = max(groups, key=len)
if len(max_group) < len(min_max_group):
min_max_group, best_guess = max_group, guess
return best_guess
H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j]))
for j in xrange(len(wordlist))]
for i in xrange(len(wordlist))]
possible = range(len(wordlist))
n = 0
while possible and n < 6:
guess = solve(H, possible)
n = master.guess(wordlist[guess])
possible = [j for j in possible if H[guess][j] == n]
# Time: O(n^2)
# Space: O(n)
class Solution2(object):
def findSecretWord(self, wordlist, master):
"""
:type wordlist: List[Str]
:type master: Master
:rtype: None
"""
def solve(H, possible):
min_max_group, best_guess = possible, None
for guess in possible:
groups = [[] for _ in xrange(7)]
for j in possible:
if j != guess:
groups[H[guess][j]].append(j)
max_group = groups[0]
if len(max_group) < len(min_max_group):
min_max_group, best_guess = max_group, guess
return best_guess
H = [[sum(a == b for a, b in itertools.izip(wordlist[i], wordlist[j]))
for j in xrange(len(wordlist))]
for i in xrange(len(wordlist))]
possible = range(len(wordlist))
n = 0
while possible and n < 6:
guess = solve(H, possible)
n = master.guess(wordlist[guess])
possible = [j for j in possible if H[guess][j] == n]