I've read this question: Why is if True slower than if 1?, but i'm using Python3 now. I am writing leetcode 204 and someone said that using one is faster than using two.
My code:
import timeit
count = 1000
def countPrimes(n=100000):
if n < 3:
return 0
primes = [True] * n
primes[0], primes[1] = False, False
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
for j in range(i * i, n, i):
primes[j] = False
return sum(primes)
def countPrimes2(n=100000):
if n < 3:
return 0
primes = [1] * n
primes[0], primes[1] = 0, 0
for i in range(2, int(n ** 0.5) + 1):
if primes[i]:
for j in range(i * i, n, i):
primes[j] = 0
return sum(primes)
print('use False,True ', timeit.timeit(countPrimes, number=count))
print('use 0,1 ', timeit.timeit(countPrimes2, number=count))
The result is:
-> % python3 test.py
use False,True 10.634566191001795
use 0,1 9.187052419991232
Can anyone tell me why?