【发布时间】:2018-04-18 05:50:31
【问题描述】:
如果我有字符串 "axplpett" 我想返回 true,因为它的子字符串 "axplpe" 包含所有苹果的字母。
本来想用set方法,但是apple有重复字符。
【问题讨论】:
-
为什么不对字符串的子串做一个简单的迭代,并检查字符串中是否包含子串的每个字母。
如果我有字符串 "axplpett" 我想返回 true,因为它的子字符串 "axplpe" 包含所有苹果的字母。
本来想用set方法,但是apple有重复字符。
【问题讨论】:
就这么简单?
string = "axplpett"
test = "apple"
all(string.count(l) >= test.count(l) for l in test)
【讨论】:
r = 'aapple'
w = list('axplpett')
try:
for x in r:
w.pop(w.index(x))
print(True) # return True
except ValueError:
print(False) # return False
【讨论】:
也许是这样的:-
def findsub (sub,main):
l1 = [i for i in sub]
l2 = [i for i in main]
for item in l1:
if item in l2:
l2.remove(item)
else:
return False
return True
print(findsub('apple','appleccssfftt'))
【讨论】:
您可以通过Counter 轻松做到这一点。
我们从测试字符串“axplpett”中的字母数中减去目标字符串“apple”中的字母数。目标字符串中不在测试字符串中的任何字母都将导致这些字母的计数为负数。然后我们否定该结果,这会去除正数或零计数,如果目标字符串包含在测试字符串中,则结果计数器将为空。
from collections import Counter
target = 'apple'
test = 'axplpett'
counts = Counter(test)
counts.subtract(target)
print(not -counts)
counts = Counter('axplett')
counts.subtract(target)
print(not -counts)
输出
True
False
【讨论】: