Anti-pattern in Python programming, Python Programming Pattern

Source: Internet
Author: User

Anti-pattern in Python programming, Python Programming Pattern

Python is one of the most popular programming languages nowadays. Simple and expressive syntax, two or three lines of code can solve the problem with more than 10 lines of C code. The rich standard library and third-party Library greatly save the development time, make it the first choice for development tasks that do not have strict performance requirements; strong and active communities, complete documentation, it also makes many Programming beginners choose it as their first programming language. It has even been reported abroad that Python has become the most popular programming entry-level teaching language in top U.S. universities.

It is not easy to learn a programming language. When you are a beginner, correct some wrong practices, which is crucial for future deep learning. A blogger named Constantine Lignos, a postdoctoral researcher at the radiology Research Department of the Children's Hospital of Pennsylvania, recently wrote a very meaningful article, lists the most common mistakes made by students who are new to Python and classifies and analyzes them. The outline of these mistakes deserves learning from every Python beginner.

This article provides some anti-patterns that are common for beginners of Python. Anti-patterns usually refer to usage that do not conform to habits or may cause bad consequences. Lignos divides the summarized anti-pattern into four categories: iteration, performance, variable vulnerabilities, and programming style. Let's take an example one by one to understand where these anti-patterns are.

Iteration

When we need to simply iterate a number range, Python gives us a very useful function: range. Lignos observed that some beginners prefer to use range to iterate the list of the following table, as shown below:

for i in range(len(alist)):    print alist[i]

This code is okay now, but it does not conform to Python's habits. But the following code has a problem:

Alist = ['her', 'name', 'is ', 'Rio'] for I in range (0, len (alist)-1 ): # The last print I, alist [I] is missing.

Let's take a look at the range example in the Python official documentation:

>>> range(1, 11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The right range is not included. If it is influenced by intuition or other programming languages, it is incorrect to subtract 1. Lignos also lists several other wrong iteration modes. We just need to remember that range should be used in a certain number range of iterations.

Performance

Lignos provides two pieces of code:

Lyrics_list = ['her', 'name', 'is ', 'Rio'] words = make_wordlist () for word in words: if word in lyrics_list: # linear time print word, "is in the lyrics"

And

Lyrics_set = set (lyrics_list) words = make_wordlist () for word in words: if word in lyrics_set: # constant time print word, "is in the lyrics"

Which mode is more efficient? The Lignos comments have provided the answer. The annotation means to determine whether an element exists in a group of elements. The complexity of the list algorithm is O (n), and the complexity of the set algorithm is O (1 ). Is set always better than list? In other cases, which data structure should be used? The official Python Wiki provides a document dedicated to the time complexity of various data structure operations for your reference. It is more important to see this document than the answer. Only the Python source code can tell us why.

Variable Vulnerability

Beginners tend to consider some premise that should not be assumed, and some abnormal procedures are not considered weekly. Lignos also provides an example:

for idx, value in enumerate(y):    if value > max_value:        breakprocessList(y, idx)

If y is null, a problem occurs. Because idx cannot be defined at all, we will get a NameError exception. It is better to give idx a default error value. In C, we often like to use-1. The following code is comprehensive:

Def find_item (item, alist): # for Python, None is better than-1. result =-1 for idx, other_item in enumerate (alist): if other_item = item: result = idx break return result
Code style

Python has a code style instruction document, PEP 8, which makes sense. When a beginner does not understand why, the best practice is to follow it as much as possible. When a beginner has a deeper understanding, he will suddenly become enlightened and his colleagues will understand when to break the rules. Lignos references some examples in this document, such as how to test whether a variable is null, and whether a variable is None.

The above analyzes some examples in this article. For more information, see the original article. To learn a programming language well, it is far from enough to learn the syntax. You must gradually understand the CPU architecture, compiler, interpreter, and virtual machine that the language depends on. Although the Lignos article does not thoroughly analyze the implementation of Python, It is very helpful for beginners. When beginners have some experience, they can explore some problems in depth, this introduces Python implementation issues.

Related Article

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.