Skip to content

Instantly share code, notes, and snippets.

@lyleaf
Last active November 23, 2015 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lyleaf/a7d988be233ef0f77f12 to your computer and use it in GitHub Desktop.
Save lyleaf/a7d988be233ef0f77f12 to your computer and use it in GitHub Desktop.
299 Bulls and Cows
Comment
https://leetcode.com/problems/bulls-and-cows/
First my solution is to loop it for once to get the dict of the secret. Then loop it for a second time.
Then I see that it can be done in one loop.
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
d = {}
bull, cow = 0,0
for index,s in enumerate(secret):
if guess[index] == s:
bull += 1
else:
d[s] = d.get(s,0) + 1
for index,s in enumerate(secret):
if (guess[index] != s) & (d.get(guess[index],0) != 0):
cow += 1
d[guess[index]] -= 1
return str(bull) + "A" + str(cow) + "B"
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
ds = {}
dg = {}
bull, cow = 0,0
for index,s in enumerate(secret):
if guess[index] == s:
bull += 1
else:
if ds.get(guess[index],0) == 0:
dg[guess[index]] = dg.get(guess[index],0) + 1
if dg.get(s,0) == 0:
ds[s] = ds.get(s,0) + 1
if ds.get(guess[index],0) != 0:
ds[guess[index]] = ds.get(guess[index],0) - 1
cow += 1
if dg.get(s,0) != 0:
cow += 1
dg[s] = dg.get(s,0) - 1
return str(bull) + "A" + str(cow) + "B"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment