import random
import numpy as np
RANGE = 1000
data = np.ones(RANGE)
data[random.randint(0, RANGE)] = random.choice([1, 42])
data = list(data)
def check_ones1():
result = True
for im in data:
if im != 1:
result = False
break
return result
def check_ones2():
return all(map(lambda x:x==1, data))
def check_ones3():
return data.count(1) == len(data)
assert check_ones1() == check_ones2() == check_ones3()
print(check_ones1())
Если один элемент - не единица:
# False
%timeit check_ones1()
69.6 µs ± 779 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit check_ones2()
94 µs ± 936 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit check_ones3()
87.7 µs ± 633 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
если все единицы:
# True
%timeit check_ones1()
93.5 µs ± 776 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit check_ones2()
124 µs ± 374 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
%timeit check_ones3()
86.9 µs ± 566 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)