Comparison of Python function and Ruby related technologies

Source: Internet
Author: User

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)

 
 
  1. >>> s = [1,2,3]  
  2. >>> d = []  
  3. >>> for i in s:  
  4. if i * i % 3 != 1:  
  5. d.append(i * i)  
  6. >>> d  
  7. [9]  
  8. >>> 

2. Traditional functional formula (Lisp)

 
 
  1. (remove-if (lambda (n) (= (mod n 3) 1))  
  2. (mapcar (lambda (n) (* n n))  
  3. '(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:

 
 
  1. >>> filter(lambda n: n % 3 != 1, map(lambda n:n*n, [1,2,3]))  
  2. [9] 

4. Ruby function:

 
 
  1. [1,2,3].map {|n| n * n}.reject{|n| n % 3 == 1}  
  2. => [9] 

After comparison, ruby is the most concise and most natural to the Problem description. The above is an introduction to the Python function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.