Friday, December 14, 2018

Creating a List of Prime Numbers with a Simple Generator Function

In working on curriculum for Introduction to Computational Economics, I like to imagine puzzles that I might have my students solve. One of these is to create a list of prime numbers. Usually I do this by using a couple of for-loops and some if statements. So today I thought, maybe I can do this with a generator. Well, it worked :)

primes = [i for i in range(2,100) if True not in [i % j == 0 for j in range(2,i)]] 
P.S. 0012 hrs CST: My wife pointed out that I need only test half of the numbers between 1 and i.  The new code is faster :)

primes = [i for i in range(2,100) if True not in [i % j == 0 for j in range(2,int(i / 2 + 1))]]

No comments:

Post a Comment