如果您想检查两个句子是否具有相同的单词(出现次数相同),您可以将句子分成单词并对其进行排序:
>>> sorted("hello world my name is foobar".split())
['foobar', 'hello', 'is', 'my', 'name', 'world']
>>> sorted("my name is foobar world hello".split())
['foobar', 'hello', 'is', 'my', 'name', 'world']
您可以在一个函数中定义检查:
def have_same_words(sentence1, sentence2):
return sorted(sentence1.split()) == sorted(sentence2.split())
print(have_same_words("hello world my name is foobar", "my name is foobar world hello"))
print(have_same_words("hello world my name is foobar", "my name is foobar world hello"))
print(have_same_words("hello", "hello hello"))
print(have_same_words("hello", "holle"))
如果大小写不重要,您可以比较小写的句子:
def have_same_words(sentence1, sentence2):
return sorted(sentence1.lower().split()) == sorted(sentence2.lower().split())
print(have_same_words("Hello world", "World hello"))
注意:您也可以使用
collections.Counter
代替
sorted
。复杂度将为
O(n)
而不是
O(n.log(n))
,但这并没有太大的区别。
import collections
可能比字符串排序需要更长时间:
from collections import Counter
def have_same_words(sentence1, sentence2):
return Counter(sentence1.lower().split()) == Counter(sentence2.lower().split())
print(have_same_words("Hello world", "World hello"))
print(have_same_words("hello world my name is foobar", "my name is foobar world hello"))
print(have_same_words("hello", "hello hello"))
print(have_same_words("hello", "holle"))
sorted(text) == sorted(pattern)
这样行吗?虽然不是很高效,但实现起来相当容易。 - Ozgur Vatanseverlen(set(text).difference(pattern)) == 0
。 - Chen A.sorted
有什么不高效的地方吗?O(n.log(n))
几乎总是足够好的,而且接近于O(n)
。你提出的问题是'abc'
和'cba'
被认为是相等的。 - Eric Duminil