Here's a crazy piece of Python code (from @driscollis) illustrating how to calculate prime numbers below 1000 in a "functional" style.
How would I write this?
๐งต
Functional programming like this can be great for minimizing lines of code. But it is also great for making your brain spin. Here is how I would initially write this (if I were fancy, I would use the Sieve of Eratosthenes):
Can we collapse this into fewer lines of code? Certainly, (the functional style already showed that) we can. One thing to realize is that lines 3-6 can be replaced with an any call:
At this point, the code is structured such that we can use a list comprehension (or generator expression). Alternatively,
we could parameterize the code into a function and convert it to a generator. Let's see the list comprehension:
Let's make it into a function:
Recognizing that the function is accumulating, we can convert it into a generator by replacing the .append call with yield, or converting the list comprehension version into a generator expression:
What code do I prefer? I try to focus on making readable code. While I understand comprehensions, I don't favor complex comprehensions and I would probably write out the for loop. Just because you can write less lines of code doesn't mean that you always should.
Thanks for reading!
Feel free to share if you learned something and follow me for more Python insights. ๐
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.