猜数字游戏。报出来每次有几个数字是在正确的位置的,多少是不正确的。先求前者,再求后者。代码如下:
class Solution(object):
def getHint(self, secret, guess):
"""
:type secret: str
:type guess: str
:rtype: str
"""
if secret == '':
return '0A0B'
a = b = 0
s = list(secret)
g = list(guess)
for i in range(len(s))[::-1]:
if s[i] == g[i]:
a = a + 1
del s[i]
del g[i]
# print s, g
for i in range(len(g))[::-1]:
if g[i] in s:
b = b + 1
s.remove(g[i])
del g[i]
# print s, g, b
return str(a) + 'A' + str(b) + 'B'