Solve the problem in a simple way

Source: Internet
Author: User

Yesterday, my colleague showed me the God-like Python code written by another colleague during the review code. Basically, it was the list comprehension plus a huge complex filter and a regular expression, and a generator function, and added a decorator to the generator function. In fact, my colleagues have written python for a few years. In review, they can only read code at one side, check the syntax manual. I have read about it, and it seems that it is intended to implement a function of reading files and parsing them.

I don't know too much details. I just think that if one thing can be completed with simple and ordered code, don't use some cool techniques, what callbacks, objects, and modes will bring complexity and increase the cost of writing, reading, and maintenance. So when you use a knife, make sure that you are lying down with your knife, instead of a chicken, the cost is too high.

Then, we found that when we searched for a string, we directly used re. search, rather than a simple and intuitive string. find, which is obviously anti-intuitive. He told his colleagues that it is not necessarily true. Who knows re. what optimizations does search perform, resulting in him/her ratio to string. search is fast, and the problem is a complicated algorithm. It is difficult to beat a simple algorithm after optimization, String. find is an extremely simple linear algorithm. Besides, you re. search can be optimized, String. find:

In [16]: str = ‘use time.time to measure the time, which is the default on Unix : use time.time to measure the time, which is the default on Unix‘In [17]: timeit str.find(‘:‘)1000000 loops, best of 3: 388 ns per loopIn [18]: timeit re.search(‘:‘, str)100000 loops, best of 3: 2.06 us per loop

Obviously, str. Find is nearly five times faster.

 

So I agree with one sentence, learning from difficulties, and using it easily.

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.