Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 23rd (weekly Summary: 2)

Source: Internet
Author: User
Tags closure iterable local time natural logarithm pack square root

Parisgabriel



Stick to a daily subscription every day. Grey often thanks for being a dead powder also wide to

Week Summer:

                     Python ai from beginner to proficient

Functional Programming:
means to solve a problem with a series of functions
Each function completes a small function, and any combination of a series of functions can be done
Big problem
The function accepts input only and produces input, without any internal state that affects the output
Reusability of functions:
If the input parameter of a function is certain, the function that returns the result must be certain
Called Reusable functions
Reentrant and non-reentrant are accesses to variables other than local variables
Functional Programming Requirements:
The Def creation function is best not to access variables outside the local scope, which can guarantee
Uniqueness of results (reentrant)
Higher order functions High order function:
The higher-order function satisfies one of the following conditions
1. function accepts one or more function parameters passed in
2. function returns a function

Neckyan function:
map,filter,sorted

Map (func, *iterables):
A new iterative object is computed using functions and each element of an iterative object as a parameter.
This iterative object generation ends when the shortest iteration object is no longer providing data

Filter (function, iterable):
Filtering iterates over the data in the object iterable, returning an iterator object, which iterates over the object
The iterable will be filtered. function functions will evaluate each element in the iterable,
Returns false to discard this data and return true to preserve this data
Sorted (iterable, Key=none, Reverse=false):
Sorts the data of the original iteration object, generating the sorted list iterable The object can be iterated
The key function is used to provide a value that will be used as the basis for sorting the reverse flag to set the
Whether to sort in descending order


Returns an iterative object function:
Range ()
Map ()
Filter ()
Reverse ()
recursive function;
The function calls itself directly or indirectly
Call yourself directly
def f ():
F ()
Call yourself indirectly
Def FA ():
FB ()
Def FB ():
FA ()
Recursion must control the number of levels of recursion and terminate recursion when the condition is met
Almost all recursion can be replaced by a while loop.
Recursive features:
Advantages:
Recursive bar problem simplification, make the idea clearer, the code is more concise
Disadvantages:
Recursive due to the impact of the system environment, when recursion deep, you may get unpredictable results
Recursion phase:
From the original problem, recursive formula recursion from unknown to known, and eventually hit the end of the recursive condition
Regression phase
The result is obtained by recursive termination condition, and the recursive formula is gradually put into reverse.
Regression to the original problem solving

Closure closure:
A closure is a variable function that references the outside of this function

Closures are objects that bind internal nesting and execution environments outside of functions

Decorator Decorators (Professional improvement article)
An adorner is a function that is used primarily to wrap another function or class
The purpose of the decoration is to not change the original name (or class) of the function.
Changing the behavior of an object
function Adorner
A function decorator refers to a function that is passed in by the adorner, and returns a function
The principle is to change the function of the original variable binding
The document string for the function:
A string that is not assigned to any variable for the first time within a function is the document string for this function

The

Module modules:
Module is a group of programs that consist of a series of data, functions, classes, etc.
module is a file, module files usually end with a. PY
Function:
Let some related data, functions, classes logically organized together, using logical structure clear
module data, functions, classes, etc. can be provided to other modules or programs to use the
module classification; The
Built-in module (builtins) can be used directly within the parser,
Standard library modules, installed Python is installed and can be used
Third-party modules (usually open source), you need to install the
users write their own modules (which can be third-party modules for others)
Import imports a module into the current module in its entirety
from import imports one or more properties of the module into the scope of the current module
From Import * Imports all properties of a module into the current module
Dir function:
dir ([object]) returns a list of strings
does not give parameters this returns a list of all variables in the current scope
built-in modules

Math Module Usage:
Import Math
# or
From Math Import *
Variable description
MATH.E base e of natural logarithm
Math.PI Pi
Function Name Description
Math.ceil (x) rounding x up, such as x=1.2, returns 2
Math.floor (x) to the X-down rounding, such as x=1.2, returns 1
MATH.SQRT (x) returns the square root of X
Math.factorial (x) to find the factorial of X
Math.log (x[, Base]) returns the logarithm of base x, and if no base is given, the natural logarithm E is the base
MATH.LOG10 (x) to calculate the logarithm of the base x 10
Math.pow (x, y) returns X**y (x's y-square)
Math.fabs (x) returns the absolute value of the floating-point number X
Angle and Radian degrees interchange
Math.degree (x) converts radians x to angles
Math.radians (x) converts angle x to radians
Trigonometric function
Math.sin (x) returns the sine of x (x is radians)
Math.Cos (x) returns the cosine of x (radians x)
Math.tan (x) returns the tangent of x (x is radians)
Math.asin (x) returns the inverse sine of x (the return value is radians)
Math.acos (x) returns the inverse cosine of x (the return value is radians)
Math.atan (x) returns the inverse tangent of x (the return value is radians)

Time Module
This module provides time-dependent functions and is always available
Time profile
The year of A.D. is from 0 o'clock A.D. January 1, 00

The first year of the computer is starting from January 1, 1970 0 o'clock, this time is 0, after each second time +1

The UTC time (coordinated Universal time) is calculated starting from Greenwich.
UTC time does not cause errors due to time zone problems

DST Daylight Saving time (daylight saving time), also known as Daylight Time, is a period after daylight correction.

Time tuple
A time tuple is a 9 integer element that consists of nine elements, from the front to the back:
Four-bit year (for example: 1993)
Month (1-12)
Day (1-31)
Hours (0-23)
Points (0-59)
Seconds (0-59)
Day of the week (0-6, Monday is 0)
New Year's Day start (1-366)
DST correction Time ( -1, 0 or 1).
Note:
If the year value is less than 100, it is automatically converted to the value after 1900
Module Name: Time
Time Module Usage:
Import time
# or
From time import xxx
# or
From time Import *
Variable description
Time.altzone Daylight Time and UTC difference (in seconds)
Time.daylight Daylight Correction Time
Time.timezone local time and UTC difference (in seconds)
The tuple of the time.tzname time zone name, the first name is the time zone name without daylight
The first name is the time zone name that is modified by daylight saving
Note: CST is Chinese standard Time (utc+8:00)

Function Name Description
Time.time () returns the floating-point number of seconds from the beginning of the computer to the current time, whichever is the UTC time
Time.sleep (secs) lets the program sleep for a period of time for a given number of seconds floating point
Time.gmtime ([secs]) converts a given number of seconds to a time tuple expressed in UTC
(Returns the current time tuple by default)
Time.asctime ([tuple]) converts a time tuple to a datetime string
Time.mktime (tuple) converts a local date-time tuple to a new epoch-second time (UTC)
Time.localtime ([secs]) converts UTC seconds to a date tuple (whichever is the local time)

System Module SYS
Run-time system-related information
SYS module's properties
Property Description
Sys.path Module Search Path path[0] is the path name of the current script, otherwise '
Sys.modules Dictionary of Loaded modules
Sys.version Version Information string
Sys.version_info named tuples for version information
Sys.platform Operating system Platform name information
SYS.ARGV command line argument Argv[0] represents the current script path name
Sys.copyright get information about Python copyright
Sys.builtin_module_names get the name of the Python built-in module (string tuple)
SYS module's function
Function Name Description
Sys.exit ([arg]) exit program, normal exit Sys.exit (0)
Sys.getrecursionlimit () Get recursive nesting hierarchy limit (depth of stack)
Sys.setrecursionlimit (n) Get and modify recursive nesting hierarchy limits (depth of stack)


$ PIP3 Install TensorFlow
Installation of third-party module TensorFlow
Must have a network command to automatically download the installation
Custom module file name must be an identifier
The loading process of the module:
1. When the module is imported, all the statements of the module will be executed
2. If a module has been imported, the statements inside the module are not re-executed when importing again

Reload the MYMODL1 module
Import Imp
Imp.reload (MYMODL1)

__doc__ Property
The document string is automatically assigned to
__file__ Property
View the current path of the module
Dir (module name)
View Module Properties
Module to import and execute the process:
1. Search for the relevant path first, find the module name. py
2. Determine if there is a. pyc file for this module. If the. PYc is newer than the. py file, load the. pyc file directly
3. Otherwise use module. py, file generation. PYC, and load execution

PYC Python Compilation
Compilation Interpretation execution
mymod.py--------> Mymod.pyc--------> Python3

The module's document string is the same as the function

__doc__ Properties of the module
This property is used to bind the module's document string

__FILE__ Properties of the module
This property is used to record the file path name of the module

__NAME__ Properties of the module
The __name__ attribute is used to record the module's own name to determine whether the main module

Main module: __name__ binding ' __main__ '
Non-main module: __name__ binding module Name

__all__ List of modules
The list of __all__ in the module is a list of strings that can be used to store exportable properties

Hidden properties of the module
Attributes that begin with ' _ ' in the module are not normally imported when the From XXX import * is imported

Standard library Module

Stochastic module random
Description
The random module is a module for simulating or generating random output.
Import Random as R

Function Name Description
R.random () returns a random real number between [0, 1]
R.uniform (A, B) returns a random real number in the interval [a, b]
R.randrange ([Start,] stop[, step]) returns the random number in range (Start,stop,step)
R.choice (SEQ) returns random elements from a sequence
R.shuffle (seq[, random]) randomly specifies the order of the sequence (unordered sequence)
R.sample (seq,n) selects n random and non-repeating elements from a sequence
Pack (Module Pack) package
A package is a management method for grouping a module into a folder's organizational form
__init__.py is a file that must exist in a regular package
__init__.py will be automatically called when package
__init__.py:
1. Write the contents of this package
2. Fill in the document string internally
3. In the __init__.py file, you can load some other modules of this package that are lazy

List of __all__ in __init__.py
Used to record which child packages or modules in this package are imported when using the FROM import * statement
__all__ list only works with from XXX import * statements
Index path order when the package is imported:
1. Search the program's current path
2. Path provided by Sys.path

Relative imports of packages:
The relative import of a package refers to the mutual import of modules within a package
Relative import cannot exceed package external
Relative imports of packages are only useful for the latter two import methods

Exception (base) except:
What is an error:
An issue in which a logic or grammar-guided program fails to perform properly
What is an exception:
is a state of an identifier for a program error
When the exception is sent, the program will no longer execute down and go to the place where the function is called.
To process this error and revert to a normal state
The effect of an exception:
Used as a signal to notify upper-level callers of errors that need to be handled
Exception handling Statements (4):
Try-except statement:
Used to accept exception notifications, catch exceptions
Try-finally statement:
Execute the statement that must be executed
Raise statement:
Send exception notification and enter the exception state
Assert statement:
Send Assertionerror-type exception notifications based on conditional selection
Why to handle the exception mechanism:
When the number of program calls is deep, passing the error message to the keynote function requires a layer return
More trouble, with the exception handling mechanism can be simpler to pass the error message

Must be an object in <> brackets

What is an iterator
Iterators are tools that access an iterative object
Iterators refer to Objects returned with the ITER (obj) function
Iterators can use the next (IT) function to get data for an iterative object
Iterators can only forward values, not back
Use the ITER function to return an iterator to an iterative object
Iterator functions Iter and next
ITER (iterable) returns an iterator from an iterative object, and Iterable must be an object that can provide an iterator
Next (iterator) gets the next record from the iterator iterator, triggering the stopiteration exception if the next record cannot be obtained

What is a generator:
A builder is an object that can provide data dynamically, and a builder object is also an iterative object
Dynamic is the active current generation of data
There are two types of generators:
1. Generator functions
2. Generator expressions
Definition of generator function
The function that contains the yield statement is the generator function, which is called to return a generator object
Yield translated to (generate or generate) dynamically generated data within the function can be one or much
Calling return in the generator function will trigger a stopiteration exception

Function:
Zip (iter1[, iter2[, ...]) returns a Zip object that is used to generate tuples, and the number of tuples is determined by the smallest iteration object
Enumerate (iterable[, start]) generates an indexed enumeration object, returning an iterative type of index-value pair (Index-value pair)
, the default index is zero-based, or it can be specified with start (Sort custom labels)

byte strings and byte arrays
Byte string bytes (also called byte sequence)
Role:
Storing data in bytes
A byte string is an immutable sequence of bytes

Bytes:
A byte is a unit of data that consists of 8 bits (bit), which is the unit of data management for the computer.
Byte is represented by an integer in the range of 0 to 255 2 * * 8-1

The constructor of the byte string bytes
Bytes () Generates an empty byte string equivalent to B '
Bytes (Integer iteration object) # Initialize a byte string with an iterative object
Bytes (integer n) generates n byte strings with a value of 0
Bytes (string, encoding= ' utf-8 ') generates a byte string by converting it to an encoding

Bytes's Operation:
+ += * *=
< <= > >= = = =!
In/not in
Indexes and slices
Len (x)
Max (x)
MIN (x)
SUM (x)
Any (x)
All (x)

The difference between bytes and STR:
Bytes Storage bytes (typically values in range (0, 256))
STR stores Unicode characters (usually values in 0~65535)


Conversion of bytes and Str
Encoding (encode)
str------------> bytes
b = S.encode (encoding= ' utf-8 ')

Decoding (decode)
Bytes----------> str
s = B.decode (encoding= ' utf-8 ')

byte array ByteArray
is a variable sequence of bytes
Constructor for byte array: ByteArray
ByteArray () Creates an empty byte array
ByteArray (integer) Initializes an array of bytes with an iterator object
ByteArray (integer iteration object) generates n byte array with a value of 0
ByteArray (String, encoding= ' utf-8 ') generates a byte array with the conversion encoding of the string
Indexes and slices
(Byte arrays support assignment of indexes and slices, rules are indexed and tile assignment rules are the same list)

Methods of ByteArray:
Ba.clear () empty
Ba.append (n) append one byte (n is an integer of 0~255)
Ba.remove (value) deletes the first occurrence of the byte and, if it does not, triggers a valueerror error
Ba.reverse () byte order reversal
Ba.decode (encoding= ' Utf-8 ') # decoded to a string
Ba.find (sub[, Start[,end]) # Find Sub

Parisgabriel:python Full Stack engineer (0 basics to Mastery) Tutorial 23rd (weekly Summary: 2)

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.