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 and3cows. The bull is8, the cows are0,1and7.
Example 2:
Input: secret = "1123", guess = "0111" Output: "1A1B" Explanation: The 1st1in friend's guess is a bull, the 2nd or 3rd1is a cow.
Note: You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
------------------------------------------------------------------------------
非常容易写错,上一个遍历一趟的版本:
from collections import defaultdict
class Solution:
def getHint(self, secret: str, guess: str) -> str:
dic = defaultdict(int)
bulls, cows = 0, 0
for a,b in zip(secret, guess):
if (a == b):
bulls += 1
else:
dic[a] += 1
if (dic[a] <= 0):
cows += 1
dic[b] -= 1
if (dic[b] >= 0):
cows += 1
return "{0}A{1}B".format(bulls, cows)

本文深入探讨了Bulls and Cows游戏的策略实现,通过具体示例展示了如何编写函数来评估猜测与秘密数字之间的匹配度,包括精确匹配(bulls)和位置错误的匹配(cows)。文章提供了Python代码示例,使用字典数据结构来高效计算匹配结果。
1167

被折叠的 条评论
为什么被折叠?



