給定字串 seq 與字符集合 aset,判斷 seq 是否包含 aset 中任一字符。需兼顧可讀性、通用性、速度。
def contain_any(seq, aset):
for c in seq:
if c in aset:
return True
return False
c in aset 若 aset 為 set 則 O(1),為 list 則 O(m);建議調用方預先轉 set。itertools.ifilter(Python 2 風格,略快但違背 Python 哲學)
import itertools
def contain_any_itertools(seq, aset):
# aset.__contains__ 即 lambda c: c in aset
for _ in itertools.ifilter(aset.__contains__, seq):
return True
return False
ifilter 改為內建 filter(返回迭代器),寫法同理。若需判斷 aset 中所有字符是否都出現在 seq 中:
def contain_all(seq, aset):
# aset - seq == 空集 表示 aset 全在 seq 中
return not set(aset).difference(seq)
L1 = [1,2,3,4]
L2 = [1,4,3,1]
contain_all(L1, L2) # True (L2 元素全在 L1)
contain_all(L2, L1) # False (L1 有 2 不在 L2)
set.symmetric_difference 取「對稱差集」
L1 = [1,2,3,4]
L2 = [3,2,4,5]
set(L1).symmetric_difference(L2) # {1, 5} —— 只屬於其中一方的元素
import timeit, string, random
seq = ''.join(random.choices(string.ascii_letters, k=1_000_000))
aset = set('aeiouAEIOU')
timeit.timeit('contain_any(seq, aset)', globals=globals(), number=10) # ~0.12s
timeit.timeit('contain_any_itertools(seq, aset)', globals=globals(), number=10) # ~0.11s
# 差異微乎其微,選可讀性最高者
for c in seq: if c in aset: return True —— 通用、短路、Pythonic。aset 為 set 以獲 O(1) 查找。not set(aset).difference(seq)。set.symmetric_difference。