例如我有
x = "dsjcosnag"
y = "dog"
print(checkYinX(y,x))
>>true
所以我想我需要使用一个while循环作为y中每个字母的计数器,然后我可以使用itetools循环遍历每个x,每个循环它会检查x == y,如果它是否会删除它,然后检查 o 中的下一个字母。
有没有更简单的方法来做到这一点?
用于collections.Counter()
转换x
和y
到多组,然后减去以查看是否所有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
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'))