सबसे वर्बोज़ समाधान हमेशा सबसे असंगत समाधान नहीं होता है। इसलिए मैं सिर्फ एक मामूली संशोधन जोड़ता हूं (कुछ अनावश्यक बूलियन मूल्यांकन को बचाने के लिए):
def only1(l):
true_found = False
for v in l:
if v:
if true_found:
return False
else:
true_found = True
return true_found
यहाँ तुलना के लिए कुछ समय हैं:
from itertools import ifilter, islice
def OP(l):
true_found = False
for v in l:
if v and not true_found:
true_found=True
elif v and true_found:
return False
return true_found
def DavidRobinson(l):
return l.count(True) == 1
def FJ(l):
return len(list(islice(ifilter(None, l), 2))) == 1
def JonClements(iterable):
i = iter(iterable)
return any(i) and not any(i)
def moooeeeep(l):
true_found = False
for v in l:
if v:
if true_found:
return False
else:
true_found = True
return true_found
मेरा आउटपुट:
$ python -mtimeit -s 'import test; l=[True]*100000' 'test.OP(l)'
1000000 loops, best of 3: 0.523 usec per loop
$ python -mtimeit -s 'import test; l=[True]*100000' 'test.DavidRobinson(l)'
1000 loops, best of 3: 516 usec per loop
$ python -mtimeit -s 'import test; l=[True]*100000' 'test.FJ(l)'
100000 loops, best of 3: 2.31 usec per loop
$ python -mtimeit -s 'import test; l=[True]*100000' 'test.JonClements(l)'
1000000 loops, best of 3: 0.446 usec per loop
$ python -mtimeit -s 'import test; l=[True]*100000' 'test.moooeeeep(l)'
1000000 loops, best of 3: 0.449 usec per loop
जैसा कि देखा जा सकता है, ओपी समाधान यहां तैनात अधिकांश अन्य समाधानों की तुलना में काफी बेहतर है। जैसा कि अपेक्षित था, शॉर्ट सर्किट व्यवहार वाले सबसे अच्छे हैं, विशेष रूप से जॉन क्लेमेंट्स द्वारा पोस्ट किए गए समाधान। कम से कम Trueएक लंबी सूची में दो शुरुआती मूल्यों के मामले के लिए।
यहाँ Trueबिल्कुल भी कोई मूल्य नहीं है :
$ python -mtimeit -s 'import test; l=[False]*100000' 'test.OP(l)'
100 loops, best of 3: 4.26 msec per loop
$ python -mtimeit -s 'import test; l=[False]*100000' 'test.DavidRobinson(l)'
100 loops, best of 3: 2.09 msec per loop
$ python -mtimeit -s 'import test; l=[False]*100000' 'test.FJ(l)'
1000 loops, best of 3: 725 usec per loop
$ python -mtimeit -s 'import test; l=[False]*100000' 'test.JonClements(l)'
1000 loops, best of 3: 617 usec per loop
$ python -mtimeit -s 'import test; l=[False]*100000' 'test.moooeeeep(l)'
100 loops, best of 3: 1.85 msec per loop
मैंने सांख्यिकीय महत्व की जांच नहीं की, लेकिन दिलचस्प बात यह है कि इस बार एफजे द्वारा सुझाए गए दृष्टिकोण और विशेष रूप से जो जॉन क्लेमेंट्स द्वारा एक बार फिर स्पष्ट रूप से बेहतर दिखाई देते हैं।