1. Iterators & Generators
2. Decorative Device
1. Basic Decorator
2. Multi-parameter adorner (learn)
3. Recursion
4. Algorithm Basics: Binary lookup, two-dimensional array conversion, bubble sort
5. Regular expressions
Iterators & Generators
Iterators
Iterators are a way to access the elements of a collection. An iterator object is accessed from the first element of the collection, knowing that all of the elements are accessed at the end. Iterators can only move forward and not back, and one of the big advantages of iterators is that they do not require that all elements in the entire iteration be ready for implementation. An iterator evaluates an element only when it iterates over it. This feature makes iterators particularly useful for facilitating large or infinite combinations, such as a few G log files.
Characteristics:
1. The visitor does not need to be concerned about the structure within an iterator, it is only necessary to continue to fetch the next content through the next () method
2. A value in the collection cannot be accessed randomly, and can only be accessed from beginning to end
3. Cannot be rolled back during access
4. Easy to recycle large data collection, save memory.
Generate an iterator as follows:
>>> a = ITER ([1,2,3,4,5,6,7,8])>>> A.__next__'__next__' of List_iterator object at 0x02ed0cf0>>>> A.__next__()1>>> A.__next_ _()2>>> A.__next__()3>>> A.__next__()4 >>> A.__next__()
View Code
Note: iterators cannot arbitrarily access a value in a collection, and can only be accessed from start to finish, and cannot be rolled back when accessed
Generator generator:
Definition: When a function call returns an iterator, the function is called the Generator (generator), and if the function contains the yield syntax, the function becomes the generator.
The code is as follows:
defTest_cash (ABC): whileabc>=0:ABC-= 100yield100Print('We 're taking the money again.') ABC= Test_cash (500)Print(ABC.__next__())Print(ABC.__next__())Print(ABC.__next__())Print('Break for a moment, take a break.')Print(ABC.__next__())
View Code
Effect: The main effect of this yield is to interrupt the function running state, and keep the interrupt state, after the interruption, the code can continue to execute, after a period of time, you can also recall this function, from the last yield of the next sentence to start execution.
In addition, it is possible to achieve the effect of concurrent operations in single-threaded situations with yield implementation (asynchronous):
The code is as follows:
Import timedef Consumer (name): print ('%s to eat buns '%name) while True: baozi = yield print ('%s bun is coming, bun to be%s Ate '% (baozi,name)) def producer (name): C = consumer (' A ') C1 = consumer (' B ') c.__next__ () c1.__next__ () print (' I'll start making buns ') for I in range: time.sleep (1) print ('%s made two buns '%name) c.send (i) C1.send (i) Producer (' Test ')
Adorner:
Python decorator see another piece of documentation.
Recursive
Characteristics
Recursive algorithm is a direct or indirect process of invoking its own method, it often makes the description of the algorithm and easy to understand.
The recursive algorithm solves the problem with the following characteristics:
(1) Recursion is the invocation of itself in a procedure or function.
(2) When using a recursive strategy, there must be a definite recursive end condition called the recursive exit
(3) Recursive algorithm is usually very indirect, but the performance of recursive algorithm is very low, so it is generally not advocated by recursive algorithm design program.
In the process of recursive invocation, the system opens up stacks for each layer's return points, local variables, etc. Recursive process is prone to stack overflow and so on, so it is generally advocated by recursive algorithm design program.
Requirements
The recursive algorithm embodies the "repetition" generally has three requirements:
One is that each call shrinks in size (usually halved)
Second, there is a close relationship between two repetitions, the previous time to prepare for the next time (usually the previous output is for the next time the input to pave)
Third, in the scale of the problem and no longer recursive calls, so each recursive call is conditional, unconditional exit recursive call will eventually fall into a dead loop.
The sample code is as follows:
Finding a data in a binary way with a large amount of data
defsearchdate (data_result,find_n): Mid= Int (len (data_result)/2) ifLen (Data_result) >1: ifFind_n <Data_result[mid]:Print('find_n in [mid] left') searchdate (data_result[:mid],find_n)elifFind_n >Data_result[mid]:Print('find_n in [mid] right') searchdate (data_result[mid:],find_n)Else: Print('find date in Data_result [%s]'%Data_result[mid])if __name__=='__main__': Dabc= List (range (1,99999)) searchdate (DABC,57668)
By using the binary algorithm, we can quickly implement the data search, especially in the case of large data volume, the effect will be better.
Algorithm Basics
1. Generate a two-dimensional array of 4*4 and rotate it instantaneously 90 degrees
# Generate a two-dimensional array
date = [[AAA for AAA in Range (4)] for BBB in range (4)]
Name = ' print '
result = Name.center (30, ' * ')
For I in Date:
Print (i)
For R_index, row in enumerate (date): # Loops through the array and gets the array subscript of the first layer
For C_index in range (R_index, len): # Gets the second layer based on the subscript of the first layer
TMP = Date[c_index][r_index] # The element to be swapped is first stored in a temporary variable
Date[c_index][r_index] = Row[c_index] # Element Exchange
Date[r_index][c_index] = tmp
Print (Result)
for R in Date:
Print (R)
################# #另外一种写法 ##################
data = [[AAA for AAA in Range (4)] for BBB in range (4)]
For I in range (data.__len__ ()):
for k in range (data.__len__ ()):
if (i>k):
temp = Data[i][k]
data[i][k]= Data[k][i]
Data[k][i]=temp
For I in data:
Print (i)
PS: For the first kind of writing is still not very understanding, late need to watch the video, deepen
2. Fibonacci Sequence algorithm:
In a nutshell, the Fibonacci sequence is the third value equals the first value + the sum of the second value, as follows:
1 2 3 5 8 13 21 34 .....
The sample code is as follows:
def calr (arg1,arg2,stop): if arg1 = = 0 :print(arg1,arg2 )= arg1 + arg2Print (ARG3) if arg3 <stop: calr (arg2,arg3,stop) calr (0,1,789)
3. Bubble sort
Sort an irregular array in order from small to large
The code is as follows:
data = [10,4,33,21,54,3,8,11,5,22,2,1,17,13,6] Print("before sort:", data) Previous=Data[0] forJinchRange (len (data)): TMP=0 forIinchRange (len (data)-1): ifData[i] > Data[i+1]: tmp=Data[i] Data[i]= Data[i+1] Data[i+1] =tmpPrint(data)Print("After sort:", data)
############### #另外一种写法 ###################
data = [11, 1231, 124, 24123, 554, 632, 591, 112, 109, 889, 100]
Print (' Before sort: ', data)
For I in range (len (data)):
for k in range (i):
If Data[i] < Data[k + 1]:
Data[i], data[k + 1] = data[k + 1], Data[i]
Print (' After sort: ', data)
Regular expressions
Grammar:
ImportRe" "generates a regular object to match, ^ represents starting from scratch [0-9] representing any number matching 0 to 9, # So here's what it means to match the string passed in, and if the first character of the string is a number, it's a match." "P= Re.compile ("^[0-9]")" "according to the regular object generated above to match the string, if the match succeeds, this m will have the value, otherwise M is none<br><br>if m: #不为空代表匹配上了" "m= P.match ('14534ABC')Print(M.group ())
You can also merge to a single line to write:
m
=
p.match(
"^[0-9]"
,
‘14534Abc‘
)
The effect is the same, the first way to do is to compile the regular, and then to do the match, the second writing is every time you execute, you need to do a cheap
If the amount of data is large, it is recommended to use the first notation, which improves performance.
Match format
Mode |
Description |
^ |
Matches the beginning of a string |
$ |
Matches the end of the string. |
. |
Matches any character, except the newline character, when re. When the Dotall tag is specified, it can match any character that includes a line feed. |
[...] |
Used to represent a set of characters, listed separately: [AMK] matches ' a ', ' m ' or ' K ' |
[^...] |
Characters not in []: [^ABC] matches characters other than a,b,c. |
Tel |
Matches 0 or more expressions. |
Tem |
Matches 1 or more expressions. |
Re? |
Matches 0 or 1 fragments defined by a preceding regular expression, not greedy |
re{N} |
|
re{N,} |
Exact match n preceding expression. |
re{N, m} |
Matches N to M times the fragment defined by the preceding regular expression, greedy way |
a| B |
Match A or B |
(RE) |
The G matches the expression in parentheses, and also represents a group |
(? imx) |
The regular expression consists of three optional flags: I, M, or X. Affects only the areas in parentheses. |
(?-imx) |
The regular expression closes I, M, or x optional flag. Affects only the areas in parentheses. |
(?: RE) |
A similar (...), but does not represent a group |
(? imx:re) |
Use I, M, or x optional flag in parentheses |
(?-imx:re) |
I, M, or x optional flags are not used in parentheses |
(?#...) |
Comments. |
(? = re) |
Forward positive qualifiers. If a regular expression is included, ... Indicates that a successful match at the current position succeeds or fails. But once the contained expression has been tried, the matching engine is not improved at all, and the remainder of the pattern attempts to the right of the delimiter. |
(?! Re) |
Forward negative qualifier. As opposed to a positive qualifier, when the containing expression cannot match the current position of the string |
(?> re) |
Match the standalone mode, eliminating backtracking. |
\w |
Match Alpha-Numeric |
\w |
Match non-alphanumeric numbers |
\s |
Matches any whitespace character, equivalent to [\t\n\r\f]. |
\s |
Match any non-null character |
\d |
Match any number, equivalent to [0-9]. |
\d |
Match any non-numeric |
\a |
Match string start |
\z |
Matches the end of the string, if there is a newline, matches only the ending string before the line break. C |
\z |
Match string End |
\g |
Matches the position where the last match was completed. |
\b |
Matches a word boundary, which is the position between a word and a space. For example, ' er\b ' can match ' er ' in ' never ', but not ' er ' in ' verb '. |
\b |
Matches a non-word boundary. ' er\b ' can match ' er ' in ' verb ', but cannot match ' er ' in ' Never '. |
\ n, \ t, et. |
Matches a line break. Matches a tab character. such as |
\1...\9 |
A sub-expression that matches the nth grouping. |
\10 |
Matches the sub-expression of the nth grouping if it is matched. Otherwise, it refers to an expression of octal character code. |
Regular expressions commonly used 5 kinds of operations
Re.match (Pattern, string) #从头匹配
Re.search (Pattern, String) # matches the entire string until a match is found
Import= Re.compile ("[0-9]"= P.search (" ASDJA21SKDJL")print(M.group ())
Re.split () #将匹配到的格式当做分隔点对字符串分割成列表
The code is as follows:
Import= Re.compile ("[0-9]"= P.split (" TESTL1TESTM2TESTC")print(m)
Re.findall () # Find all the characters to match and return to the list format
Import rep = Re.compile ("[0-9]") m = P.findall ("Asdja21skdjlasdlajd1lajd 2 sadkljsal3 jalksjd2") print (m)
The output is as follows: [' 2 ', ' 1 ', ' 1 ', ' 2 ', ' 3 ', ' 2 ']
Re.sub (self, REPL, String, count=0) # replace match to character
Import= Re.compile ("[0-9]"= p.sub ("& ","asdja21skdjlasdlajd1lajd 2 sadkljsal3 jalksjd2", count=5) Print(m)
Regular expression Instance character matching
Example |
Description |
Python |
Match "Python". |
Character class
Example |
Description |
[Pp]ython |
Match "python" or "python" |
Rub[ye] |
Match "Ruby" or "Rube" |
[Aeiou] |
Match any one of the letters within the brackets |
[0-9] |
Match any number. Similar to [0123456789] |
[A-z] |
Match any lowercase letter |
[A-z] |
Match any uppercase letter |
[A-za-z0-9] |
Match any letters and numbers |
[^aeiou] |
All characters except the Aeiou letter |
[^0-9] |
Matches characters except for numbers |
Special character Classes
Example |
Description |
. |
Matches any single character except "\ n". To match any character including ' \ n ', use a pattern like ' [. \ n] '. |
\d |
Matches a numeric character. equivalent to [0-9]. |
\d |
Matches a non-numeric character. equivalent to [^0-9]. |
\s |
Matches any whitespace character, including spaces, tabs, page breaks, and so on. equivalent to [\f\n\r\t\v]. |
\s |
Matches any non-whitespace character. equivalent to [^ \f\n\r\t\v]. |
\w |
Matches any word character that includes an underscore. Equivalent to ' [a-za-z0-9_] '. |
\w |
Matches any non-word character. Equivalent to ' [^a-za-z0-9_] '.
|
Fourth day of Python learning