首页 > 解决方案 > 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)+')'

标签: python

解决方案


最简单的方法可能是首先计算所有共同元素,这可以通过collections.Counterhttps://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)

推荐阅读