我要檢查,如果一組單詞出現在另一組單詞,例如計數器在python集合包中使用的算法?
list1=['Hello','World']
list2=['Hello','World','Good','Bye']
我寫了下面的代碼,以檢查是否出現在列表1的話也出現在列表2
def check(list1,list2):
for l in list1:
if l not in list2:
return False
return True
但這代碼失敗的大input.Then我發現下面的代碼在其淨值適用於所有的輸入
from collections import Counter
def check(list1,list2):
return not (Counter(list1) - Counter(list2))
誰能告訴我什麼algorit hm不會使用或提供任何其他方法,使用相同的結果可以在不使用內置函數的情況下實現。
您可以檢查出的[代碼](HTTPS://hg.python。 org/cpython/file/3.6/Lib/collections/__ init__.py)。雖然毫無疑問的一些實現是在C中。它提到'multiset'並給出了一些參考鏈接。 –