An example analysis of anti-pattern in Python programming _python

Source: Internet
Author: User
Tags in python

This example describes the anti-pattern in Python programming. Share to everyone for your reference. The specific analysis is as follows:

Python is one of the hottest programming languages of all. Concise and expressive grammar, two or three lines of code tend to solve a problem that can be solved by a dozen lines of C code, rich standard libraries and third-party libraries that greatly save development time and make it the first choice for development tasks that have no stringent requirements for performance; powerful and active communities, complete documentation, Also allows many programming beginners to choose it as their first programming language. Even foreign reports say Python has become the most popular programming language in America's top universities.

To learn a programming language is not easy, in the beginner stage, correcting some wrong practices, the future of in-depth study is essential. A blogger named Constantine Lignos, a postdoctoral researcher at the radiation Research Department at the Pennsylvania Children's Hospital, recently wrote a very interesting article that enumerates the most common mistakes of students of the beginner Python, and classifies and analyzes them, and their content sketchy , and is well worth learning for every Python beginner.

This article gives some examples of anti patterns that are common in Python beginners, which often refer to usages that do not conform to the habit or that can lead to bad results. Lignos his summary of the inverse model into four categories-iterations, performance, variable vulnerabilities and programming style . Let's take a look at an example to see where the reverse patterns really are.

First, iterative

When we need to simply iterate over a range of numbers, Python gives us a very useful function: range. Lignos observed that some beginners like to use range to iterate the following table in a list, as in the following form:

Copy Code code as follows:
For I in range (len (alist)):
Print Alist[i]

This code is not a problem now, but it's not in the habit of Python. But the following code has a problem:
Copy Code code as follows:
Alist = [' Her ', ' name ', ' is ', ' Rio ']
For I in range (0, Len (alist)-1): # missing the last one
Print I, Alist[i]

We can look at an example of the official Python document range:
Copy Code code as follows:
>>> Range (1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

The right range is not included, and if it is influenced by intuition or other programming languages, minus 1 is wrong. Lignos also enumerates several other error iterations, as long as we keep in mind that range should be used in an iterative range of quantities.

Second, performance

Lignos gives two pieces of code:

Copy Code code as follows:
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
Copy Code code as follows:
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 annotation has given the answer. Annotation means to judge whether an element exists in a set of elements, the algorithm complexity of using list is O (n), and the algorithm complexity of using Set is O (1). Is that set always better than list? In other cases, which data structure should be used? The Python official wiki has a document dedicated to the time complexity of each data structure operation, and it is more important to refer to this document than the answer itself. As for why, only Python's source code can tell us.

Iii. vulnerability of variables

Beginners often assume that some assumptions are not the premise of some of the abnormal process of thinking poorly. Lignos also gave an example:

Copy Code code as follows:
For IDX, value in Enumerate (y):
If value > Max_value:
Break
Processlist (y, idx)

Here y if it's empty, then there's a problem, because IDX doesn't get a definition at all, and eventually we get a Nameerror exception. A good practice is to give IDX a default error value, in C language we often like to use-1. The following code is considered more comprehensive:
Copy Code code as follows:
def find_item (item, alist):
# None for Python-1 may be better
result =-1
For IDX, Other_item in Enumerate (alist):
If Other_item = = Item:
result = IDX
Break
return result

Four, code style

Python has a code-style guide to document PEP 8, and these rules make sense. When the scholar did not understand why, the best way is to keep it as far as possible, wait until a deeper understanding will be enlightened, colleagues will understand when can break the rules. Lignos cites some examples of this document, such as how to test whether a variable is empty, if you test whether a variable is none, and so on.

The above analysis of some of the examples in this article, if you want to fully understand, please check the original. To learn a programming language well, it is not enough to learn grammar, you must gradually understand the CPU architecture, compiler/interpreter/virtual machine and so on that language relies on. Lignos This article although not in-depth analysis of the implementation of Python, but for beginners help is very obvious, when the scholar had some experience, to some problems can be done in-depth excavation, lead to the problem of Python implementation level.

I hope this article will help you with your Python programming.

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.