The first algorithm coding standard reference work --python and "mathematical beauty" Book

I. Description

In order to standardize the writing Python code, improve code readability, the coders better on the code of cooperation, the development of this specification.

Coding standard role:

  • Improve readability  - "Any fool can write code that a computer can understand, the only way to write the code easier to understand human beings, is the good programmers." Coding standards, help us to write code that's easy to understand humans .
  • Global unity, promote teamwork - development is a team activity, rather than individual heroism.
  • Contribute to knowledge transfer, speed up the transfer of work  - the similarity of style, allowing coders faster, easier to understand some of the strange code more quickly understand someone else's code.
  • The name of reducing proliferation, reduce maintenance costs  - in the absence of norms, it is easy different names for the instances of the same type.
  • To emphasize the relationship between variables, reducing the chance of defects introduced  - named may represent a certain logic, allowing developers to be vigilant when in use, thereby reducing the chance of defects are introduced to some extent.
  • Improve individual capacity

Second, content

1. Code Layout

1.1 indentation

Recommended to four spaces as an indentation level.

1.2 expressions and statements spaces

1. leading space (indentation)
of the most popular Python indentation is to use only spaces, only tabs followed. For new projects, you should only use spaces instead of tabs.
2. Non leading spaces
non-leading spaces in the Python is not the meaning of the code, but is suitably added non-leading spaces can improve readability:
( 1) In the spaces before and after the binary arithmetic, logical operators, such as:

** Example: **

a = b + cif a and b:

    pass

( 2) no space in the unary prefix operators, such as:

** Example: ** IF FLG:! Pass

( 3) ":" before and after the end of the line when neither spaces, such as branches, loops, functions and classes defined language; rear end when the end of a line in a non-spaces, as defined dict object:

** Example: **

d = {*'key'*: *'value'*}

( 4) brackets (including parentheses, brackets, and braces) before and after no space, such as:

** Example: **

do_something(arg1, arg2)

( Plus a 5) after the comma space, no space in front.

1.3 The maximum length of the line

The maximum length of each line must not exceed the standard 80 characters. More than 80 characters, we recommend the following manner folding one long line into a plurality of short lines:
( 1) long for a short name for the variable names, such as:

** Error writing: ** ** this.is.a.very.long.variable_name = this.is.another.long.variable_name correct wording: **

variable_name1 = this.is.a.very.long.variable_name

variable_name2 = this.is.another.variable_name

variable_name1 = variable_name2

( 2) in parentheses after the delimiter (including parentheses, brackets, and braces) of wrap, such as:

** Example: ** the Edit ** ** class (Base):

    def **__init__**(*self*, parent, width,

    font = FONT, color = BLACK, pos = POS, style = 0): # NOTE: This line remains the same line with the indent

        pass

( 3) addition of a long line continuation character forcibly break a line, the line should break position before the operator, such as:

** Example: ** IF Color or Color == == WHITE BLACK \ == or Color BLUE: # Note: Wrap and maintain the same first line indent (or not indented)

    do_something(color)

1.4 blank line

Enter an empty row, the following general principles:
( 1) between different types of modules import add a blank line;
( 2) plus blank line between functions and classes defined in the top layer;
( 3) defined between the classes and class CSA lines;
( 4) defined between the function and the function line CSA;
( 5) was added a blank line between the class definition line and the first method definition thereof;
( 6) is applied between the logic functions of the paragraph blank line, i.e., the code associated with the write compact, as a logical paragraph, separated by blank lines between paragraphs.

1.5 encoding

All Python script file should be in the file header # - - Coding: utf8 - -; the editor is used to set the default save as utf8 format:

#-*- coding:utf8 -*-

2. Statement

2.1 standard head

Using the following general standard header statements:

#!/usr/bin/python

If you need to use a custom Python compiler environment, it can be used similar to the following header statements:

#!/usr/bin/env python2.7

Description: The role of the bank statement is to help find the core Python interpreter, but are often ignored when importing Python modules; only when directly executing a single file, the statement is necessary.

2.2 Import (Import)

1. normally be introduced in a separate line (Import), for example, "1 correct wording"; if desired, introducing a plurality of classes from a module in a row, can be referred to "correct wording 2":

** Error writing: ** Import SYS, os ** correct wording **** 1 **** : ** ** Import sysimport os correct wording **** 2 **** : ** Import types from StringType , ListType

2. the position and import statement introduced sequence
generally will import statements at the top of the file, and only after the module annotated documents string, before the global variables and constants module. Import statement should be sequentially placed into groups:
( 1) First, import standard library (built-in module);
( 2) Next, the module of the third party (third party reference packet);
( 3) Finally, introducing their development projects the other modules;
in each group is placed between the lead a blank line.
3. The method of introducing class
from a class containing import module class can generally be written as:

**示例:**from MyClass import MyClassfrom foo.bar.YourClass import YourClass

If the above wording led to the local name clashes, then write:

** Example: **

import MyClass

import foo.bar.YourClass

Then use MyClass.MyClass and foo.bar.YourClass.YourClass way you can.

2.3 Assignment

For the assignment language, mostly do not do unnecessary alignment, such as:

** Error writing: **

a = 1VAR = 2

fn = callback_function ** correct wording: **

a = 1VAR = 2

fn = callback_function

Branching and looping 2.4

Various branching and looping statements do not write a line, such as:

** Error writing: ** IF FLG:! I passfor in xrange (10): Print i ** correct wording: ! ** IF FLG:

    passfor i in xrange(10):

    print i

3. Comment

When code changes, always prioritize the update notes. Comments should be complete sentences, if the comment is a phrase or sentence, the first letter should be capitalized, unless he is beginning with a lowercase letter identifier (if the Chinese comments may ignore this requirement).

3.1 Comment Block

Comment blocks are often used to follow some code and code and have the same indentation level. Comment block in each row are "#" and a space to start. Between paragraphs in the comment block segmented to contain only a single "#" line. On each comment block is preferably below a blank line.

3.2 line comments

Inline comment is a comment and statements in the same line. Comments should use at least two separate spaces and statements within the line, and should be "#" and start a single space, such as:

** Example: **

x = x + 1  # Increment x

If semantics are clear, then the inline comments are unnecessary.

3.3 docstrings

Documenting a string for all public modules, functions, classes and methods. Documentation string of non-public methods are not necessary, but it should have a comment describing the effect of this approach. This comment should be "def" line after.
It must be noted that at the end of multi-line documentation string . "" "Should make the trip alone, for example:

**示例:***"""Return a foobang*

*Optional plotz says to frobnicate the bizbaz first*

*"""*

For single-line documentation string, ending with "" "may be on the same line, for example:

*"""Return a foobang"""*

Notes version 3.4

Note release can refer to the following sample code:

** Example: **

__version__ = *"$Revision: 1.4 $"*

This should be included in the line after the document module string, until all code , divided vertically by a blank line.

3.5 Module Notes

Each module should contain the following items comments, are:
( 1) the copyright notice;
( 2) the content of the comment module, including module description, description of classes and methods in the module, version and maintenance information;
( 3) a statement of , the author identifies the file;

**示例:**# Copyright (C), 2010-2013, China Standard Software Co., Ltd.*"""*

*FileName: Test.py*

* Author: fei.liu *

*Version: 0.1*

*Date: 2013-02-27*

* Description: ** Overview module with a line of text or script, by the end of the period. *

* ClassFoo: ** line overview of the use of class module. *

* FunctionBar (): ** line overview of the use of the function module. *

* History: / * ** ** history modify records * / *

*<Author>   <Date>   <Version>   <Desc>*

* Fei.liu 2013-03-04 1.0 Release *

*"""*

__authors__ = [

  *'"John Smith" <[email protected]>'*,

  *'"Joe Paranoid" <[email protected]>'*,]

3.6 functions and methods Notes

Any function or method requires a documentation string for the function or method of any externally accessible, documentation string is particularly important.
Documents should contain a detailed description of the string action function, and the parameters, inputs and outputs:
( . 1) the Args: a detailed description of the input parameters; if the data type requires a specific parameter or a default value of the parameter is provided, it should be in the document character string explicitly described;
( 2) returns: output (return) specifically described data;
( . 3) Raises: Give all the function may trigger abnormal;

** Example: ** ** fetch_bigtable_rows DEF ** (BIG_TABLE, Keys, other_silly_variable = None): * "" "** taken a number of lines in the table *

*    Retrieves rows pertaining to the given keys from the Table instance*

*    represented by big_table.  Silly things may happen if*

*    other_silly_variable is not None.*

*    Args:*

*        big_table: An open Bigtable Table instance.*

*        keys: A sequence of strings representing the key of each table rowto fetch.*

*        other_silly_variable: Another optional variable, that has a much*

*            longer name than the other args, and which does nothing.*

*    Returns:*

*        A dict mapping keys to the corresponding table row data fetched.*

*Each row is represented as a tuple of strings. For example:*

*        {'Serak': ('Rigel VII', 'Preparer'),*

*         'Zim': ('Irk', 'Invader'),*

*         'Lrrr': ('Omicron Persei 8', 'Emperor')}*

*        If a key from the keys argument is missing from the dictionary,*

*        then that row was not found in the table.*

*    Raises:*

*        IOError: An error occurred accessing the bigtable.Table object.*

*    """*

    pass

3.7 Class Notes

There must be a class definition below for describing the document class string ( docstring). If the class has public properties (Attributes), it should explain the significance of these documents in a string of public property.

**示例:**class **SampleClass**(object):

    *"""Summary of class here.*

*    Longer class information....*

*    Longer class information....*

*    Attributes:*

*        likes_spam: A boolean indicating if we like SPAM or not.*

*        eggs: An integer count of the eggs we have laid.*

*    """*

    def **__init__**(*self*, likes_spam=False):

        *"""Inits SampleClass with blah."""*

        *self*.likes_spam = likes_spam

        *self*.eggs = 0

    def **public_method**(*self*):

        *"""Performs operation blah."""*

4. Naming Convention

4.1 Description: Naming Convention

Prohibit the use of the character "l", "O" or "I" as a single-character variable names. These characters can not be separated from the numbers 1 and 0 in some fonts region.

4.2 module name

The module name without underscores should have short, lowercase names; for only the default package ( module used in the Packages), can be prefixed with an underscore, such as:

** Example: **

module.py

_internal_module.py

4.4 class name

Class name using CapWords convention (capitalized word, do not use underscore word, not adding C, T, etc. prefix); internal use of the class need to add a leading underscore before the name, such as:

**示例:**class **ThisIsAClass**(object):passclass _**ThisIsAClass**(object):pass

4.5 exception name

Exception name using CapWords naming convention (capitalized word, do not use underscore word).

4.6 variables, constants, global variable names

Python typically by "from M import *" to import content (variables, classes, functions, etc.) from the module, the global variables must be prefixed (internal functions or classes) is derived which prevents (Exporting) with an underscore.
1. Constant
constant name in all uppercase letters, each connected by underlining words, such as:

** Example: **

WHITE = 0XFFFFFF

THIS_IS_A_CONSTANT = 1

2. Variable
( 1) all lowercase variable names, each connected by underlining words, such as:

** Example: **

color = WHITE

this_is_a_variable = 1

( 2) whether the class member variable or a global variable is not used by the prefix m or g. Private class members to use a single underscore prefix identification;
( 3) the variable name with the type of information should not be, because Python is dynamically typed languages; such as iValue, names_list, dict_obj, etc. are bad name.
3. Global variables
must be prefixed with an underscore global variables prevent it from being exported.

4.7 function name

Function names should be lowercase, it can be used to increase the readability of the underlined word style.

4.8 method names and instance variables

And substantially the same function naming: typically use lowercase words, separated by underscores as necessary to improve readability.
If you are not going to internal methods and instance open to the public, you need to use a leading underscore at the beginning of the name.
Use two leading underscores to indicate the name of the class private members. Leading usually double underscore attribute containing only be used to avoid name conflicts subclass of class.

4.9 specific naming

Mainly it refers to xxx in the form of a reserved word nomenclature system. The project can also use this name, its significance lies in this form of the variable is read-only, this form of class member functions so as not to overload. Such as:

** Example: ** ** Base ** class (Object):

    def __**init**__(*self*, id, parent = None):

        *self*.__id__ = id

        *self*.__parent__ = parent

    def __**message**__(*self*, msgid):

        # ...

Which _ the above mentioned id , parent and message have adopted the system of reserved words nomenclature.

5. inherited design

Always To determine whether a class instance variables and methods to be disclosed. Typically, never the data variables public unless the record but essentially you realize, people always prefer to provide a function for the class interface to implement modify data variables.
Also, determine if your property should be private. Proprietary and non-proprietary difference is: the former will never be used in a derived class, while the latter may be. You should be in the brain to use good design to inherit your class :( 1) private property must have two leading underscores, no rear underline; (2) non-public property must have a leading underscore, no rear underline; ( 3) public property no leading underscore the post, unless they conflict with reserved words, in this case, a single rear underscore better than the front or confusing spelling, for example: class_ better than klass.

6. Design Recommendations

Individual elements ( Comparative singletons), as None should be used "is" or "is not". When you purported "if x is not None" when, to write "if x" to be careful. For example, when you test whether a default is None of the variables or parameters be set to other values, the other values may be False in a boolean context (Boolean context).
Class-based exceptions are always better than the exception-based string. Modules and packages should define their own domain-specific base exception class, the base class should be built subclass Exception class, but also always a document that contains the string class. E.g:

**示例:**#!/usr/bin/Pythonclass(Exception)*"""Base class for errors in the email package."""*MessageError

Use string method ( Methods) in place of the module string, unless be backward compatible with previous versions Python 2.0. Always very fast string method, and a unicode string, and share the same API (Application Programming Interface), to avoid slicing the string while checking the prefix or suffix. With startswith () and endswith () in place, such as the probability of error is smaller. E.g:

** Error writing: **

if foo[:3] == *'bar'*:

** correct wording: **

if foo.startswith(*'bar'*):

In special cases, if your code must work in Python 1.5.2, compare types of objects should always use isinstance () instead of direct comparison type, for example:

** Error writing: ** IF of the type (obj) IS of the type (1): ** correct wording: ** IF isinstance (obj, int):

Check whether an object is a string, keep in mind that it might be unicode strings! In Python 2.3, str and unicode have a common base class basestring, so you can do this:

if isinstance(obj, basestring):

In Python 2.2 StringTypes types defined for this module type, for example:

#!/usr/bin/Pythonfrom types import StringTypesif isinstance(obj, StringTypes):

For sequences (strings, lists, tuples), use an empty list is false that fact, so "if not seq" or "if seq" than "if len (seq)" or "if not len (seq)" it is good. Do not rely on significant trailing space when writing a string literal. This rear space is visually indistinguishable and some editors will trim them off. Do not use "==" to compare Boolean values to determine True or False (Boolean is new in Python2.3):

** Error writing: ** IF the Greeting == True: ** correct wording: ** IF the Greeting:

 

Reference Links: https://www.jianshu.com/p/9694dd841b42

          https://blog.csdn.net/ratsniper/article/details/78954852

          https://www.runoob.com/w3cnote/google-python-styleguide.html

 

 

"Mathematical beauty" book review section probation

"Mathematical beauty" of this book a lot of space, roughly told, there are more than 400 pages, is not easy to read at a very busy week. So, I only a part of probation.

Trial down, can not say that there is a deep sentiment, but this book is really interesting, using a large number of well-known interesting example to illustrate the principles of jerky hard to understand. Most importantly, the book conveys a very important idea: to explain the principles of computer use mathematical principles, and mathematical thinking to be transformed.

This shows that the application of mathematical ideas in programming and algorithm design occupied a pivotal position, is an indispensable thing. But also that a good computer engineer is also a mathematician from the side.

 

 

 

This semester wanted to software implementation:

This term would like to achieve a community can automatically retrieve the appropriate software according to the input keyword.

This software mainly to the number of workers engaged in the network operators can obtain a more convenient working environment. At the same time we want to be able to use python to accomplish such a software.

Guess you like

Origin www.cnblogs.com/jumaodangdawang/p/11442190.html