Bulls and Cows LeetCode solution in Python

1
class Solution:
2
def getHint(self, secret: str, guess: str) -> str:
3

4
# Setup counts for bulls and cows
5
bulls = cows = 0
6

7
# Copy secret and guess into lists that are easier to work with
8
secretCopy = list(secret)
9
guessCopy = list(guess)
10

11
# In a for loop, check every pair of letters at the same index in both guess and secret for matching letters, AKA bulls
12
for i in range(len(secret)):
13

14
# If they match, bulls += 1 and pop() the letters from the copy lists via their .index()
15
if secret[i] == guess[i]:
16
bulls += 1
17
secretCopy.pop(secretCopy.index(secret[i]))
18
guessCopy.pop(guessCopy.index(guess[i]))
19

20
# Count() the letters remaining in secret and guess lists
21
secretCounter = Counter(secretCopy)
22
guessCounter = Counter(guessCopy)
23

24
# Counter1 - Counter2 gives us Counter1 with any matching values of Counter1 and Counter2 removed; leftover Counter2 values are trashed
25
# secretCounter - guessCounter gives us the secretCounter except for any correctly guessed letters
26
# Therefore, subtract this difference from the OG secretCounter to be left with a counter of only correctly guessed letters
27
dif = secretCounter - (secretCounter - guessCounter)
28

29
# The .total() of the dif Counter is the number of cows
30
cows = dif.total()
31

32
# return the formatted string with req. info
33
return f"{bulls}A{cows}B"

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0