博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode299. Bulls and Cows(思路及python解法)
阅读量:2241 次
发布时间:2019-05-09

本文共 1536 字,大约阅读时间需要 5 分钟。

You are playing the following  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.

Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows. 

Please note that both secret number and friend's guess may contain duplicate digits.

Example 1:

Input: secret = "1807", guess = "7810"Output: "1A3B"Explanation: 1bull and 3cows. The bull is 8, the cows are 0, 1 and 7

小时候经常玩的猜数字游戏。

先比对完全正确猜对的,也就是A。

然后利用两个字典,统计猜的各个数字个数以及正确的各个数字个数。

这样对于同一个数字,既存在于guess又存在于secret,出现次数最少的就是B。

class Solution:    def getHint(self, secret: str, guess: str) -> str:        s={}        g={}        a=b=0        for i in range(len(secret)):            if secret[i]==guess[i]:                a+=1            else:                s[secret[i]]=s.get(secret[i], 0)+1                g[guess[i]]=g.get(guess[i], 0)+1        for i in g:            if i in s:                b+=min(g[i],s[i])                return '{}A{}B'.format(a,b)

当然也看到了大神的三行代码。

s, g = Counter(secret), Counter(guess)    a = sum(i == j for i, j in zip(secret, guess))    return '%sA%sB' % (a, sum((s & g).values()) - a)

 

转载地址:http://gdrbb.baihongyu.com/

你可能感兴趣的文章
Oracle PL/SQL语言初级教程之完整性约束
查看>>
PL/SQL学习笔记
查看>>
如何分析SQL语句
查看>>
结构化查询语言(SQL)原理
查看>>
SQL教程之嵌套SELECT语句
查看>>
日本語の記号の読み方
查看>>
计算机英语编程中一些单词
查看>>
JavaScript 经典例子
查看>>
判断数据的JS代码
查看>>
js按键事件说明
查看>>
AJAX 设计制作 在公司弄的 非得要做出这个养的 真晕!
查看>>
Linux 查看文件大小
查看>>
Java并发编程:线程池的使用
查看>>
redis单机及其集群的搭建
查看>>
Java多线程学习
查看>>
检查Linux服务器性能
查看>>
Java 8新的时间日期库
查看>>
Chrome开发者工具
查看>>
【LEETCODE】102-Binary Tree Level Order Traversal
查看>>
【LEETCODE】106-Construct Binary Tree from Inorder and Postorder Traversal
查看>>