python - Python计算列表中元素的数量,但不在正确的位置,没有重复
问题描述
我想要以下内容:
In [1]: check('ABCD', 'ABCD')
Out[1]: (4, 0)
In [2]: check('AAAA', 'ABCD')
Out[2]: (1, 0)
In [3]: check('AADA', 'ABCD')
Out[3]: (1, 1)
In [4]: check('ADDA', 'ABCD')
Out[4]: (1, 1)
In [5]: check('ADDB', 'ABCD')
Out[5]: (1, 2)
函数检查有两个参数,第一个是猜测,第二个是正确的代码。
在“Out”中,第一个数字是正确位置的正确字母数。
第二个是正确字母的数量,但不在正确的位置。
使用我的代码,我可以毫无问题地找到第一个数字,但第二个数字给我带来了困难,因为我无法想出一个不计算重复的代码。
即:如果我这样做check('ADDB', 'ABCD')
了,(1,4)
因为它在正确的位置计数一个(不应该),两个'D'(应该算作 1 )和 B(这个没问题)。
这里的代码:
def check(guess, code):
cInCode = 0 # letter in code but wrong place
cInPlace = 0 # right letter & right place
for x in range(0, len(code)):
if code[x]==guess[x]:
cInPlace += 1
cInCode += code.count(guess[x])
return '('+str(cInPlace)+','+str(cInCode)+')'
解决方案
最简单的方法可能是首先计算所有共同元素,这可以通过collections.Counter
(https://docs.python.org/3/library/collections.html#collections.Counter)来完成。如果然后减去正确位置的元素,您将得到常见但位置错误的元素。
from collections import Counter
def common_elements(guess, code):
# Counter() makes frequency counts
# "&" intersects them (counting the elements in common)
# .values() takes only the counts, and sum() adds them up
return sum((Counter(guess) & Counter(code)).values())
def right_place(guess, code):
# zip() iterates over pairs of elements
# eg zip('ABC', 'DEF') yields ('A', 'D'), ('B', 'E'), ('C', 'F')
return sum(a == b for a,b in zip(guess, code)) # assumes same length!
def wrong_place(guess, code):
return common_elements(guess, code) - right_place(guess, code)
推荐阅读
- sql - 如何从上一行引用计算值以查找下一个计算值
- c# - 在使用 autofac 实现接口的程序集中注册一个泛型类型
- apache-kafka - Kafka vs ActiveMQ Artemis 的内存使用和稳定性
- .net - 是什么导致 SELECT 错误附近的语法不正确?
- aws-lambda - 无服务器框架忽略 lambda-proxy 设置中的“授权者”块
- postgresql - 如何将 AWS RDS 安全组中的 Zapier IP 地址列入白名单
- bash - Bash - 变量 - bash -c 命令
- django - 在 Django 中缓存模型属性
- perl - 捕获通过管道从另一个 perl 脚本调用的 perl 脚本的输出
- html - 如何使用 HTML/CSS/JS 定位屏幕?