There are a lot of interesting things in the Python function. Next we will take a detailed look at the technical comparison between the Python function and Ruby. Next, let's take a look at how to apply it. I hope you will have some gains.
What is the use of Python functional programming? I think the practical advantage is that we can better describe the problem, rather than describe the operation steps to solve the problem. Let's look at a specific example:
Problem: A list. For each element, the square is removed from the list if the remainder of the square number is 1.
See the solution:
1. Traditional procedural (Python functional)
- >>> s = [1,2,3]
- >>> d = []
- >>> for i in s:
- if i * i % 3 != 1:
- d.append(i * i)
- >>> d
- [9]
- >>>
2. Traditional functional formula (Lisp)
- (remove-if (lambda (n) (= (mod n 3) 1))
- (mapcar (lambda (n) (* n n))
- '(1 2 3)))
It can be seen that the functional program corresponds to the two steps we mentioned, which are implemented by mapcar and remove-if respectively. But the Lisp program is really not very easy to read. We use python and ruby to improve it:
3. Python function:
- >>> filter(lambda n: n % 3 != 1, map(lambda n:n*n, [1,2,3]))
- [9]
4. Ruby function:
- [1,2,3].map {|n| n * n}.reject{|n| n % 3 == 1}
- => [9]
After comparison, ruby is the most concise and most natural to the Problem description. The above is an introduction to the Python function.