Kemp’s Blog

A technical blog about technical things

Extreme Python

So if you ever want a function in Python that can generate all the prime numbers up to n and for some reason you want to do it in one line of code you need not look any further than this. Of course, once you’ve used this code sample you may feel dirty, and documenting it in a nice way is a challenge left for the reader.

def primes(n): return filter(lambda num : not bool(filter(lambda x : num % x==0, range(2, num / 2))), range(2, n))

I have Sarah to blame for the inspiration for this one (section 10.2.3 of her 112CR notes =P), though she at least used a couple more lines to split it into two functions and some more lines for documentation since it was possible with her example. Completely self-contained functional programming for the win, and as a bonus due to my version being a single line it’s easily turned into another lambda function and embedded into something else, I’m sure there’s probably a competition out there for getting things done in a single line of code.

Edit:
As an aside, I quite like random.Random().random(), it has something of a feeling of deja vu about it.