-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy path299_bulls_and_cows.py
More file actions
61 lines (49 loc) · 1.36 KB
/
299_bulls_and_cows.py
File metadata and controls
61 lines (49 loc) · 1.36 KB
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
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if not secret or not guess or len(secret) != len(guess):
return ''
TMPL = '{}A{}B'
bulls = 0
cows = 0
cnts = [0] * 10
for i in range(len(secret)):
s = ord(secret[i]) - ord('0')
g = ord(guess[i]) - ord('0')
if s == g:
bulls += 1
continue
cnts[s] += 1
cnts[g] -= 1
if cnts[s] <= 0:
cows += 1
if cnts[g] >= 0:
cows += 1
return TMPL.format(bulls, cows)
class Solution:
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if not secret or not guess or len(secret) != len(guess):
return ''
TMPL = '{}A{}B'
bulls = 0
cows = 0
cnt_s = [0] * 10
cnt_g = [0] * 10
for i in range(len(secret)):
if secret[i] == guess[i]:
bulls += 1
else:
cnt_s[int(secret[i])] += 1
cnt_g[int(guess[i])] += 1
for i in range(10):
cows += min(cnt_s[i], cnt_g[i])
return TMPL.format(bulls, cows)