# 3 lines in Python

• ``````def getHint(self, secret, guess):
bulls = sum(map(operator.eq, secret, guess))
both = sum(min(secret.count(x), guess.count(x)) for x in '0123456789')
return '%dA%dB' % (bulls, both - bulls)``````

• map(operator.eq...), never thought that.......

• Elegant as always!

• Hi, Stefan, cool `both`! I try to rewrite it in C++ and I only come up with `multiset`. Do you have some nicer ways?

``````class Solution {
public:
string getHint(string secret, string guess) {
int bull = 0, both = 0, n = secret.length();
for (int i = 0; i < n; i++)
bull += (secret[i] == guess[i]);
multiset<char> s(secret.begin(), secret.end()), g(guess.begin(), guess.end());
for (char c = '0'; c <= '9'; c++)
both += min(s.count(c), g.count(c));
}
};``````

• @jianchao.li.fighter Haha, my `both` is the part I don't like. It's still O(n), but 10 passes over each string isn't exactly nice. It's just short and simple.

For C++ I don't really have nicer ways than multiset, although

``````    for (char c = '0'; c <= '9'; c++)
both += min(count(begin(secret), end(secret), c),
count(begin(guess), end(guess), c));
``````

is 2-3 times faster than yours and a bit shorter.

• Really nice `count` :-)

• This post is deleted!

• Using these digits('7807', '7810'),the result is 2A1B, is it wrong?

• 2A1B is correct, the first 7 and 8 are bulls, and 0 is the cow.

• there is no need to use min.

``````def getHint(self, secret, guess):
bulls = 0
bucket = [0]*10
for s, g in zip(secret, guess):
if s == g:
bulls += 1
else:
bucket[int(s)] += 1
bucket[int(g)] -= 1
return '%sA%sB' % (bulls, len(secret) - bulls - sum(cnt for cnt in bucket if cnt>0))
``````

let c = len(secret) - bulls

diff = sum(cnt for cnt in bucket if cnt>0)

0 == sum(bucket)

it can be easily verified that, in two counter solution

let x denote sum of max, cows be sum of min, then

x + cows = 2*c

x - cows = 2*diff

thus cows = c - diff

remove of bulls is not necessary, similar conclusion holds

• nice and thank you~

• Wow, that is simply amazing. Thank you for this. Any book you'd recommend to improve this kind of python thinking?

• Quite similar:

``````def getHint(self, secret, guess):
A = sum(a==b for a,b in zip(secret, guess))
B = collections.Counter(secret) & collections.Counter(guess)
return "%dA%dB" % (A, sum(B.values()) - A)``````

• Elegant solution. Not like mine:

``````    string getHint(string secret, string guess) {
int A=0,B=0;
int n = secret.size();
vector<bool> vis(n);
for (int i = 0; i < n; ++i) {
if (guess[i] == secret[i]) {
A++;
if (vis[i]) {
B--;
for (int j = 0; j < n; ++j) {
if (j==i)continue;
if (!vis[j] && guess[i] == secret[j]) {
B++;
vis[j]=true;
break;
}
}
}
else vis[i]=true;
} else {
for (int j = 0; j < n; ++j) {
if (j==i)continue;
if (!vis[j] && guess[i] == secret[j]) {
B++;
vis[j]=true;
break;
}
}
}
}