I will use my example: I want to create a list of primes using the sieve of Eratosthenes. For each number, I check if it is composite, and if not, I append it to the list.
Using "standard" programming:
primes = [2] start = time.time() for i in xrange(3,primeRange,2): isPrime = True for p in primes: if(i % p == 0): isPrime = False break; if(isPrime): primes.append(i) print "Using C++-style: ", time.time() - start, " seconds"
Using
reduce
function:start = time.time() for i in xrange(3,primeRange,2): if(reduce(lambda x,y:x and y,[i % p != 0 for p in primes])): primes.append(i) print "Using map-reduce: ", time.time() - start, " seconds"
The results for primeRange = 100000
:
Using map-reduce: 54.1150000095 seconds
Using C++-style: 4.62000012398 seconds
The 2nd case makes the code more compact, but the condition will be evaluated for the entire list and then reduced to True
/ False
. Is there a way to avoid that?