Giải pháp dài dòng nhất không phải lúc nào cũng là giải pháp nhẹ nhàng nhất. Do đó, tôi chỉ thêm một sửa đổi nhỏ (để tiết kiệm một số đánh giá boolean dư thừa):
def only1(l):
true_found = False
for v in l:
if v:
if true_found:
return False
else:
true_found = True
return true_found
Dưới đây là một số thời gian để so sánh:
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
Đầu ra của tôi:
$ 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
Có thể thấy, giải pháp OP tốt hơn đáng kể so với hầu hết các giải pháp khác được đăng ở đây. Như mong đợi, những giải pháp tốt nhất là những giải pháp có hành vi ngắn mạch, đặc biệt là giải pháp được đăng bởi Jon Clements. Ít nhất là đối với trường hợp hai Truegiá trị ban đầu trong một danh sách dài.
Ở đây giống nhau không có Truegiá trị nào cả:
$ 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
Tôi đã không kiểm tra ý nghĩa thống kê, nhưng thú vị là lần này các phương pháp tiếp cận do FJ đề xuất và đặc biệt là phương pháp của Jon Clements lại tỏ ra vượt trội hơn rõ ràng.