-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBulls and Cows.py
58 lines (44 loc) · 1.77 KB
/
Bulls and Cows.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# Link: https://leetcode.com/problems/bulls-and-cows/submissions/
"""
Bull (A)- Correct digit at correct place
Cow (B) - Correct digit at incorrect place
"""
class Solution:
def getHint(self, secret: str, guess: str) -> str:
# If secret and guess match, return string
if secret == guess:
return "{}A0B".format(len(secret))
# Turn both strings to lists
secretList = list(secret)
guessList = list(guess)
# Create counters
aCounter = 0
bCounter = 0
# Iterate string to look for matching positions
for i in range(len(secret)):
# Look for matching pair
if secret[i] == guess[i]:
# Increment counter
aCounter += 1
# Remove element from both lists
secretList.remove(secret[i])
guessList.remove(guess[i])
# Rename lists based on size
if len(secretList) >= len(guessList):
maxList = secretList
minList = guessList
else:
maxList = guessList
minList = secretList
# Iterate both lists
for i in range(len(minList)):
for j in range(len(maxList)):
# If an identical number is found, pop element from maxList
if minList[i] == maxList[j]:
bCounter += 1
maxList.pop(j)
break # <= Exit inner loop to update i
if len(maxList) == 0: # <= In case both list have equal length
break
# Return string
return "{}A{}B".format(aCounter, bCounter)