leetcode299

来源:互联网 发布:重庆双成网络 编辑:程序博客网 时间:2024/05/16 07:44

类似猜数字的游戏,输入两个四位数secret和guess,返回位置和大小都对的数字个数和只对大小位置不对的个数。

class Solution(object):    def getHint(self, secret, guess):        A=0        B=0        for i in range(len(secret)):            if secret[i]==guess[i]:                A+=1            for j in range(len(secret)):                if secret[i]==guess[j]:                  B+=1        B=B-A        print(A)        print(B)

使用counter模块。

class Solution(object):    def getHint(self, secret, guess):        """        :type secret: str        :type guess: str        :rtype: str        """        bull = sum(map(operator.eq, secret, guess))        sa = collections.Counter(secret)        sb = collections.Counter(guess)        cow = sum((sa & sb).values()) - bull        return str(bull) + 'A' + str(cow) + 'B'

import collections
可以使用collections.Counter统计值出现了多少次。
返回Counter({字典})
返回的这个特殊类型可以&操作,求相同部分。values取数值,然后求和可以算出总共重复出现的数字有多少个。再减去BULL值就是B的值了。
operator函数里面eq是比较两个变量是否相同。需要import operator库。

0 0
原创粉丝点击