Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
loops vs vs set comprehensions
# find all prime numbers up to N using the sieve of Eratosthenes
N = 100000
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
primes_loop = set(range(2, N))
for i in range(2, int(N**0.5)+1):
for j in range(i**2, N, i):
primes_loop.discard(j)
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tLoop = time.perf_counter() - t
print(f'{tLoop:.5f} sec')
t = time.perf_counter()
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
primes_setcomp = set(range(2,N)) - {j for i in range(2, int(N**0.5)+1) for j in range(i**2, N, i)}
# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
tComp = time.perf_counter() - t
print(f'{tComp:.4f} sec: set comprehension vs loop: {100*(tComp/tLoop-1):.1f}%')
assert primes_loop == primes_setcomp
primes_list1 = [p for p in primes_loop if p < 100]
primes_list2 = [p for p in primes_setcomp if p < 100]
df = pd.DataFrame([primes_list1, primes_list2])
df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment