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
- leetcode299
- [leetcode299]Bulls and Cows
- leetcode299. Bulls and Cows
- LeetCode299. Bulls and Cows
- Leetcode299. Bulls and Cows
- leetcode299. Bulls and Cows
- LeetCode299——Bulls and Cows我的解法
- HttpClient学习整理
- java.lang.Class.getDeclaredMethod()方法
- Android中的支付(银联篇)
- 关于用xib创建静态tableview可能会用到的一些委托函数
- 跳转到距锚点固定位移的地方
- leetcode299
- 全球最杰出的14位程序员
- UIView的autoresizingMask详解
- Unity3D 基地实现(摄像机移动、拖动建筑等)
- 分享下自己写的二次方程计算器(python)
- Linux 终端访问 FTP 及 上传下载 文件
- 废话一二
- 操作系统期末考点大纲
- 机器学习算法的归类