You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
Write a function to return a hint according to the secret number and friend's guess, use A
to indicate the bulls and B
to indicate the cows.
Please note that both secret number and friend's guess may contain duplicate digits.
Example 1:
Input: secret = "1807", guess = "7810" Output: "1A3B" Explanation: 1bull and 3cows. The bull is 8, the cows are 0, 1 and 7
小时候经常玩的猜数字游戏。
先比对完全正确猜对的,也就是A。
然后利用两个字典,统计猜的各个数字个数以及正确的各个数字个数。
这样对于同一个数字,既存在于guess又存在于secret,出现次数最少的就是B。
class Solution:
def getHint(self, secret: str, guess: str) -> str:
s={}
g={}
a=b=0
for i in range(len(secret)):
if secret[i]==guess[i]:
a+=1
else:
s[secret[i]]=s.get(secret[i], 0)+1
g[guess[i]]=g.get(guess[i], 0)+1
for i in g:
if i in s:
b+=min(g[i],s[i])
return '{}A{}B'.format(a,b)
当然也看到了大神的三行代码。
s, g = Counter(secret), Counter(guess)
a = sum(i == j for i, j in zip(secret, guess))
return '%sA%sB' % (a, sum((s & g).values()) - a)