【LEETCODE】299-Bulls and Cows

来源:互联网 发布:求一个矩阵的k次方 编辑:程序博客网 时间:2024/06/08 07:02

You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.

For example:

Secret number:  "1807"

Friend's guess: "7810"

Hint: 1 bull and3 cows. (The bull is 8, the cows are0, 1 and7.)


Write a function to return a hint according to the secret number and friend's guess, useA to indicate the bulls and B to indicate the cows. In the above example, your function should return"1A3B".

Please note that both secret number and friend's guess may contain duplicate digits, for example:

Secret number:  "1123"

Friend's guess: "0111"

In this case, the 1st 1 in friend's guess is a bull, the 2nd or 3rd1 is a cow, and your function should return"1A1B".


You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.


题意:

写一个数字,让朋友猜这个数是什么

每次猜完之后,给出提示:

如果数字及其位置都是一致的,是bull,用A表示

如果数字正确但是位置不对,是cow,用B表示


例如:

Secret number:  "1807"

Friend's guess: "7810"

返回:1A3B

Secret number:  "1123"

Friend's guess: "0111"

返回:1A1B


思路:

bull:按位比较 secret 和 guess,数字相等的,就是bull

Counter:统计字符串中 各个字符及其出现的次数

Counter(s1)&Counter(s2): 字符及其次数 的交集

cow:字符及次数 的交集-字符及位置想等的个数


参考:

http://bookshadow.com/weblog/2015/10/31/leetcode-bulls-and-cows/


python3中替换python2中cmp函数的新函数分析(lt、le、eq、ne、ge、gt)

http://blog.csdn.net/sushengmiyan/article/details/11332589

operator.eq(a, b)

eq(a,b) 相当于 a == b

3.4.3又没有这些函数了,直接用==,>=,<=就行

#字符及次数 的交集

>>> secret='7810'>>> guess='1178'>>> sa=Counter(secret)>>> sb=Counter(guess)>>> saCounter({'0': 1, '8': 1, '7': 1, '1': 1})>>> sbCounter({'1': 2, '8': 1, '7': 1})>>> sa&sbCounter({'8': 1, '7': 1, '1': 1})>>> (sa&sb).values()dict_values([1, 1, 1])



from collections import Counterclass Solution(object):    def getHint(self, secret, guess):        """        :type secret: str        :type guess: str        :rtype: str        """                bull=0                for i in range(len(secret)):                #判断 字符及位置相等            if secret[i]==guess[i]:                bull+=1                sa=Counter(secret)                          #统计 字符出现的次数        sb=Counter(guess)                cow=sum((sa&sb).values())-bull              #字符及次数 的交集                return str(bull)+'A'+str(cow)+'B'

0 0
原创粉丝点击