最良の答えは確かに
print 'yay' if any(c in '0123456789' for c in var) else ':('
その理由は誰でも簡単に理解できる
編集 1
いいえ、以下の方法の中で最も遅い方法なので、ベストアンサーではありません。
私は正規表現が大好きですが、正規表現を使用したソリューションが最速のものになるとは想像できませんでした。
set() を使用する方が高速です。
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 23, 1564.'''
from time import clock
import re
n = 1000
te = clock()
for i in xrange(n):
b = any(c in ('0123456789') for c in var)
print clock()-te
ss = set('0123456789')
te = clock()
for i in xrange(n):
b = ss.intersection(var)
print clock()-te
te = clock()
for i in xrange(n):
b = re.search('\d',var)
print clock()-te
regx = re.compile('\d')
te = clock()
for i in xrange(n):
b = regx.search(var)
print clock()-te
結果
0.157774521622
0.0335822010898
0.0178648403638
0.00936152499829
編集 2
ジョーブで!
実際、シェンセイの答えは最良の答えです。
私が想像していたものとは正反対です!
from time import clock
import re
n = 1000
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
結果
0.00467852757823
var byの探索for dig in var
は本当に超高速であると結論付けています。
私はそれが非常に速いことだけを知っていました。
編集 3
shensei のソリューションの実行時間は、分析された文字列の内容に依存することを誰も指摘していません。
from time import clock
n = 1000
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 00, 0000.'''
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
var = '''For all his fame and celebration, William Shakespeare remains a mysterious figure
with regards to personal history. There are just two primary sources for information
on the Bard: his works, and various legal and church documents that have survived from
Elizabethan times. Naturally, there are many gaps in this body of information, which
tells us little about Shakespeare the man.
William Shakespeare was born in Stratford-upon-Avon, allegedly on April 99, 9999.'''
te = clock()
for i in xrange(n):
b = any(dig in var for dig in '0123456789')
print clock()-te
結果を出す
0.0035278226702
0.0132472143806
0.00936152499829 秒かかる ompiled regex の使用は、最悪の場合、shensei のソリューションよりも速いようです。しかし実際には、正規表現をコンパイルする時間を測定時間に含めると、実際の実行時間は 0.0216940979929 秒になります。
その場合、shensei のソリューションは依然として最速の方法です。