From: https://towardsdatascience.com/the-next-level-of-functional-programming-in-python-bc534b9bdce1 Useful Python tips and tricks to take your functional skills to the next level![]()
Python is one of the world’s most popular and in-demand programming languages. Indeed, if you are in the hot field of Data Science, Python is, most probably, your daily driver. But why?
However, this story is not for beginners. Some experience with the language is required to understand the examples and their value. Thus, without further ado let’s dive into the
DefinitionsEvery function that we examine here is part of Python’s
count(start=10, step=1) --> 10 11 12 13 14 ...
islice('ABCDEFG', 2, None, 1) --> C D E F G
tee(it, [n=2])
repeat(elem=10, n=3) --> 10 10 10
cycle('ABCD') --> A B C D A B C D ...
chain('ABC', 'DEF') --> A B C D E F
accumulate(p=[1,2,3,4,5], func=add) --> 1 3 6 10 15
As we said, to make something out of these primitive functions, we would have to compose them and create higher abstractions. So let’s do that and create our Custom extensionsTo begin with, let’s create a function to realize the first def take(it, n):
As we do that, let’s also create a function that removes the first def drop(it, n):
Now, we are able to create our own primitive functions, that return the head = next
If you haven’t use Next, we want to create a new function, that we will call compose. It works like that: compose(x, f) --> x, f(x), f(f(x)), f(f(f(x))), ...
So, how can we do that? It turns out we can do this very efficiently now that we have yielded the power of the def compose(x, f):
I admit it looks a bit complex, but if you squint hard enough, you’ll understand its inner workings. take(compose(2, lambda x: x**2), 5) --> [2, 4, 16, 256, 65536]
Putting it all togetherNow, we are onto something here! So let’s use some functions that we have defined to create the infamous Fibonacci numbers sequence. def next_num(pair): Let’s walk it through step by step. The compose function creates a sequence of tuples. The first tuple is take(fibonacci(), 10) --> [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
This is a super-efficient implementation of the Fibonacci sequence, which runs under 35μs! It showcases the power of good, functional design! |
Python >