0

例如我有

x = "dsjcosnag"
y = "dog"

print(checkYinX(y,x))
>>true

所以我想我需要使用一个while循环作为y中每个字母的计数器,然后我可以使用itetools循环遍历每个x,每个循环它会检查x == y,如果它是否会删除它,然后检查 o 中的下一个字母。

有没有更简单的方法来做到这一点?

4

2 回答 2

8

用于collections.Counter()转换xy到多组,然后减去以查看是否所有y的字母都可以在 中找到x

from collections import Counter

def checkYinX(y, x):
    return not (Counter(y) - Counter(x))

减去多重集会在字符数降至 0 时删除False字符。如果这导致多重集为空,则它会变成布尔上下文,就像所有“空”python 类型一样。not如果是这样True的话。

演示:

>>> x = "dsjcosnag"
>>> y = "dog"
>>> print(checkYinX(y,x))
True
>>> print(checkYinX('cat',x))
False
于 2013-03-29T14:47:49.810 回答
1

collections.Counter根据聊天中的要求,这是一种不带 的方法:

def countLetters(word):
    d = {}
    for l in word:
        d[l] = d.get(l,0) + 1
    return d

def checkSubset(answer,letters):
    a, l = countLetters(answer), countLetters(letters)
    return all(l.get(x,0) >= a.get(x) for x in a.keys())

print(checkSubset('dog','odr'))
于 2013-03-30T23:22:55.477 回答