Python Learning Path The next day-iterators, generators, Algorithm basics

Source: Internet
Author: User

First, iterators:

Iterators are a way to access the elements of a collection.

The iterator object is accessed from the first element of the collection until all the elements have been accessed and finished.

Iterators can only move forward without going backwards, but that's fine, because people seldom retreat in the middle of an iteration.

In addition, one of the great advantages of iterators is that they do not require that all elements in the entire iteration be prepared in advance. An iterator computes an element only when it iterates over it, and before or after that, the element may not exist or be destroyed. This feature makes it ideal for traversing large or infinite collections, such as several G files

Characteristics:

    1. The visitor does not need to care about the structure inside the iterator, but simply continues 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. You can't go back halfway through the interview.
    4. Facilitates recycling of large data sets, saving memory

1. Create an iterator:

x = iter ([1, 2, 3, 4])print(x) above instance output result:<list_iterator object at 0x000000000107c1d0>
iterators (ITER)

2. Iterator Operation:

__next__() function: is the value within the iterator: x= ITER ([1, 2, 3, 4])Print(x.__next__())Print(x.__next__())Print(x.__next__())Print(x.__next__())Print(x.__next__()) The result of the above instance output:1234Traceback (most recent): File"e:/project/s12/day1/test.py", line 11,inch<module>Print(x.__next__()) Stopiteration Note: When the values in the iterator are all taken out, the error is reported as above. 
value (__next__ ())

Second, generator (yield):

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.

defcash_out (amount): whileAmount >0:amount-= 1yield1Print("wipe, again to collect money ... Black sheep! ") ATM= Cash_out (3)Print("take money to%s million"% ATM.__next__())Print("take the flowers out!")  Print("take money to%s million"% ATM.__next__())Print("take money to%s million"% ATM.__next__()) Above example output: Take Money1million flowers out of the flower, wipe, again to collect money ... Black sheep! Take the money .1million rub, again to take the money ... Black sheep! Take the money .1million Note: The yield function allows one loop to perform another operation in half, and then back to the loop to continue execution. 
yield

Role:

The main effect of yield is that the function can be interrupted, and save the interrupt state, after the break, the code can go to perform other operations, the other operation is completed, you can also recall this function, from the last yield of the next sentence to start execution.

3. Yield receive parameters:

Yield implements the effect of concurrent operations in single-threaded situations:

Import TimedefConsumer (name):Print("%s ready to eat buns!"%name) whileTrue:baozi=yield       Print("Bun [%s] came, eaten by [%s]!"%(baozi,name))defproducer (name): C= Consumer ('A') C2= Consumer ('B') c.__next__() c2.__next__()    Print("Lao Tzu began to prepare steamed buns!")     forIinchRange (3): Time.sleep (1)        Print("made 2 buns!") c.send (i) c2.send (i) Producer ("Earl") The above example output: A ready to eat steamed buns! B prepare to eat steamed buns! I began to make steamed buns! Made 2 buns! steamed Bun [0] came, was [A] eaten! Bun [0] came, was [B] ate! Made 2 buns! Bun [1] came, and was [a] eaten! Bun [1] Come, be [B] eat! Made 2 buns! steamed Bun [2] came, and was [a] eaten! Bun [2] came, and was [B] eaten!
send to yield pass parameters:

Three, the adorner:

Requirements: When we developed an interface, this interface is provided to the user, but in the use of the process need to add a function, without changing the interface call mode and code, add this function, how to do? It's time for the decorator to play.

defLogin (func):defx (user):ifuser = ='Earl':            returnfunc (user)returnX@logindefTV (name):Print('Welcome to%s, come to TV channel'%name) TV ('Earl') above example output: Welcome Earl, come to TV channel
Adorner Instance

Example of an adorner passing parameter:

defbefore (Request):Print('before')defAfter (request):Print(' After')defFilter (before_func,after_func):defouter (main_func):defWrapper (Request): Before_result=Before_func (Request)if(Before_result! =None):returnBefore_result; Main_result=Main_func (Request)if(Main_result! =None):returnMain_result; After_result=After_func (Request)if(After_result! =None):returnAfter_result; returnwrapperreturnOuter@filter (before, after)defIndex (Request):Print('Index') Index ('Example') The result of the above instance output: Beforeindexafter
Adorner pass parameters:

Description: A function if the function name plus parentheses such as func () is the function that performs func, if no parentheses such as Func said is to take the Func function memory ID value, do not execute function, in the iterator a lot of return call is just the function name. So pay more attention to this in the iterator.

Iv. recursion:

Characteristics

Recursive algorithm is a direct or indirect process to invoke its own algorithm. In the computer programming, the recursive algorithm is very effective to solve a large class of problems, it often makes the description of the algorithm concise and easy to understand.
The recursive algorithm solves the problem characteristic:
(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 a recursive exit.
(3) Recursive algorithm is usually very concise, but the recursive algorithm is less efficient in solving problems. Therefore, the recursive algorithm is generally not advocated for the design of the program.
(4) in the process of recursive invocation, the system opens up a stack for each layer's return point, local quantity and so on to store. Too many recursion times can cause stack overflow and so on. Therefore, the recursive algorithm is generally not advocated for the design of the program.

1, the use of functions to write the following series:

Fibonacci numbers refer to such a sequence of 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368

def func (Arg1, arg2):     if arg1 = = 0        :print(arg1, arg2    )= arg1 +    arg2if Arg3 <:        print(arg3)        func (arg2, Arg3) func (0,1  112358
Recursive instances:

2, by recursion to achieve 2 points to find:

defBinary_search (data_list,find_num): Mid_pos= Int (len (data_list)/2) Mid_val=Data_list[mid_pos]Print(data_list)ifLen (data_list) >= 1:        ifMid_val >Find_num:Print("[%s] should is in left of [%s]"%(Find_num,mid_val)) Binary_search (Data_list[:mid_pos],find_num)elifMid_val <Find_num:Print("[%s] should is in right of [%s]"%(Find_num,mid_val)) Binary_search (Data_list[mid_pos:],find_num)Else:             Print("Find", Find_num)Else:        Print("cannot find [%s] in Data_list"%find_num)if __name__=='__main__': Primes= List (range (1,20)) Binary_search (primes,10)    Else:        Print("cannot find [%s] in Data_list"%find_num)if __name__=='__main__': Primes= List (range (1,30)) Binary_search (primes,10The result of the above instance output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29][should beinchLeft of [15][1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14][should beinchRight of [8][8, 9, 10, 11, 12, 13, 14][should beinchLeft of [11][8, 9, 10][should beinchRight of [9][9, 10]find10
2 points Find an instance:

Five, the basic algorithm:

Generates a 4*4 2-d array and rotates it 90 degrees clockwise

Array=[[col forColinchRange (5)] forRowinchRange (5)]#Initializes a 4*4 array forRowinchArray#look at the number leader before you spin .    Print(Row)Print('-------------') forI,rowinchEnumerate (array): forIndexinchRange (I,len (ROW)): TMP=Array[index][i] Array[index][i]=Array[i][index]Print(Tmp,array[i][index]) Array[i][index]=tmp forRinchArrayPrint(R)Print('--one Big Loop--'The result of the above instance output: [0,1, 2, 3, 4][0,1, 2, 3, 4][0,1, 2, 3, 4][0,1, 2, 3, 4][0,1, 2, 3, 4]-------------0 XX1020304[0, 0, 0, 0, 0][1, 1, 2, 3, 4][2, 1, 2, 3, 4][3, 1, 2, 3, 4][4, 1, 2, 3, 4]--one Big Loop--1 11 21 31 4[0, 0, 0, 0, 0][1, 1, 1, 1, 1][2, 2, 2, 3, 4][3, 3, 2, 3, 4][4, 4, 2, 3, 4]--one Big Loop--2 22 32 4[0, 0, 0, 0, 0][1, 1, 1, 1, 1][2, 2, 2, 2, 2][3, 3, 3, 3, 4][4, 4, 4, 3, 4]--one Big Loop--3 33 4[0, 0, 0, 0, 0][1, 1, 1, 1, 1][2, 2, 2, 2, 2][3, 3, 3, 3, 3][4, 4, 4, 4, 4]--one Big Loop--4 4[0, 0, 0, 0, 0][1, 1, 1, 1, 1][2, 2, 2, 2, 2][3, 3, 3, 3, 3][4, 4, 4, 4, 4]--one Big Loop--
4*4 2-D array instance:

Python Learning Path The next day-iterators, generators, Algorithm basics

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.