>>> s = 'AAAAAAAAAAAAAAAAAAA'
>>> s.count(s[0]) == len(s)
True
これは短絡しません。短絡を行うバージョンは次のようになります。
>>> all(x == s[0] for x in s)
True
ただし、最適化された C 実装により、一部の文字列 (サイズなどに応じて) では、おそらく非短絡バージョンの方がパフォーマンスが向上するのではないかと感じています。
timeit
投稿された他のオプションのいくつかをテストするための簡単なスクリプトを次に示します。
import timeit
import re
def test_regex(s,regex=re.compile(r'^(.)\1*$')):
return bool(regex.match(s))
def test_all(s):
return all(x == s[0] for x in s)
def test_count(s):
return s.count(s[0]) == len(s)
def test_set(s):
return len(set(s)) == 1
def test_replace(s):
return not s.replace(s[0],'')
def test_translate(s):
return not s.translate(None,s[0])
def test_strmul(s):
return s == s[0]*len(s)
tests = ('test_all','test_count','test_set','test_replace','test_translate','test_strmul','test_regex')
print "WITH ALL EQUAL"
for test in tests:
print test, timeit.timeit('%s(s)'%test,'from __main__ import %s; s="AAAAAAAAAAAAAAAAA"'%test)
if globals()[test]("AAAAAAAAAAAAAAAAA") != True:
print globals()[test]("AAAAAAAAAAAAAAAAA")
raise AssertionError
print
print "WITH FIRST NON-EQUAL"
for test in tests:
print test, timeit.timeit('%s(s)'%test,'from __main__ import %s; s="FAAAAAAAAAAAAAAAA"'%test)
if globals()[test]("FAAAAAAAAAAAAAAAA") != False:
print globals()[test]("FAAAAAAAAAAAAAAAA")
raise AssertionError
str.count
私のマシン (OS-X 10.5.8 、core2duo、python2.7.3) では、これらの不自然な (短い) 文字列を使用set
してall
、 と をstr.replace
少し叩きますが、追い抜かれstr.translate
、strmul
現在は十分なマージンでリードしています:
WITH ALL EQUAL
test_all 5.83863711357
test_count 0.947771072388
test_set 2.01028490067
test_replace 1.24682998657
test_translate 0.941282987595
test_strmul 0.629556179047
test_regex 2.52913498878
WITH FIRST NON-EQUAL
test_all 2.41147494316
test_count 0.942595005035
test_set 2.00480484962
test_replace 0.960338115692
test_translate 0.924381017685
test_strmul 0.622269153595
test_regex 1.36632800102
タイミングは、異なるシステム間および異なる文字列でわずかに (または大幅に?) 異なる可能性があるため、渡す予定の実際の文字列を調べる価値があります。
最終的に、最適なケースがall
十分にヒットし、文字列が十分に長い場合は、それを検討することをお勧めします。それはより良いアルゴリズムです...set
ソリューションを打ち負かす可能性があるケースは見当たらないので、私はソリューションを避けcount
ます。
str.translate
メモリが問題になる可能性がある場合は、str.replace
を避ける必要がありますstrmul
。これらは 2 番目の文字列を作成するためですが、最近では通常、これは問題になりません。