两个问题的区别在于是否判断元素的数量
问题一:字符串s是否含有字符串t所有种类元素
- 实例一:
s='a'
t='aaa'
print(set(t).issubset(set(s)))
"""
输出结果:
True
"""
- 实例二:
s='asdeef'
t='easf'
print(set(t).issubset(set(s)))
"""
输出结果:
True
"""
问题二:字符串s包含字符串t所有元素
- 实例一:
from collections import Counter
s='a'
t='aa'
dict_s=dict(Counter(s))
dict_t=dict(Counter(t))
print(dict_s)
print(dict_t)
result=True
for n, m in dict_t.items():
if n not in dict_s or dict_s[n]<m:
result=False
break
print(result)
"""
输出结果:
{'a': 1}
{'a': 2}
False
"""
- 实例二:
from collections import Counter
s='asdeef'
t='easf'
dict_s=dict(Counter(s))
dict_t=dict(Counter(t))
print(dict_s)
print(dict_t)
result=True
for n, m in dict_t.items():
if n not in dict_s or dict_s[n]<m:
result=False
break
print(result)
"""
输出结果:
{'a': 1, 's': 1, 'd': 1, 'e': 2, 'f': 1}
{'e': 1, 'a': 1, 's': 1, 'f': 1}
True
"""
|