List generation review and builder exercises, Yang Hui triangle instances (very ingenious)

Source: Internet
Author: User

List-Generated

Print('Review--------------------yesterday') d= {'a': 1,'b': 2,'C': 3} forKeyinchD:Print(Key) forValueinchd.values ():Print(value) forKvinchD.items ():Print(k, v) forChinch 'ABC':    Print(CH) fromCollectionsImportIterablet= Isinstance (123, iterable)#checks whether an iteration is possible, the return value is a Boolean type ofPrint(t) forI, ValueinchEnumerate (['A','B','C']):    Print(i, value) forX, yinch[(1, 1), (2, 4), (3, 9)]:    Print(x, y) L= List (range (100))PrintL

Build generator

Print('Build Generator--------------------')#with List generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted. #So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the generator: Generator. L = [x*x forXinchRange (10)]Print(L) G= (x * x forXinchRange (10))Print(G)#If you want to print one, you can get the next return value for generator by using the next () function:Print(Next (G))Print(Next (G))Print(Next (G))Print(Next (G))Print(Next (G))Print(Next (G)) 01491625#This constant call to next (g) is so perverted that the correct approach is to use a For loop because generator is also an iterative object:g = (x*x forXinchRange (10)) forNinchg:Print(n)

Implementing Generators with functions

Print('implement generator--------------------with functions')#generator is very powerful. If the algorithm is more complex, it can also be implemented by using a function that is not possible with a For loop that resembles a list-generated type. deffib (max): N, a, b= 0, 0, 1 whileN <Max:Print(b) A, B= B, A +B N= n + 1return ' Done'#the above function can output the number of the first n of the Fibonacci sequence:t = fib (6)Print(t)#in other words, the above functions and generator are only a step away. To turn the FIB function into a generator, simply change print (b) to yield B:deffib (max): N, a, b= 0, 0, 1 whileN <Max:yield(b) A, B= B, A +B N= n + 1return ' Done'fib (11)#This sentence has no result, you can receive the return value with one parameter and then output#This is another way to define generator. If a function definition contains the yield keyword, then the function is no longer a normal function, but a generator:F = fib (6)Print(f)#<generator object fib at 0x104feaaa0>Print('--------------------')#The most difficult thing to understand here is that the generator is not the same as the execution flow of the function. The function is executed sequentially, the return statement is encountered, or the last line function statement is returned. The function that becomes generator, executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned. #To give a simple example, define a generator and return the number 1,3,5 in turn:defOdd ():Print('Step 1')    yield1Print('Step2')    yield(3)    Print('Step 3')    yield5o=Odd ()Print('next output odd generator content--------------------')Print(Next (o))Print(Next (o))Print(Next (o))Print('iterate output fib generator content--------------------') forNinchFIB (6):    Print(n)Print('outputs all the contents of the generator with the return value----------')#However, when you call generator with a For loop, you find that you cannot get the return value of the generator return statement. If you want to get the return value, you must catch the Stopiteration error, and the return value is contained in the value of Stopiteration:g = FIB (6) while(True):Try: x=Next (g)Print('g:', X)exceptstopiteration as E:Print('Generator return value:', E.value) Break; 

Output of the Yang Hui Triangle

Print('output-----------------of the Yang Hui Triangle')#God, this code, too incisive, I have nothing to saydefFun (n): N= [1] t=0 whileT <N:yield(N) T= t + 1n.append (0) N= [N[i-1] + n[i] forIinchRange (len (N))] forIinchFun (6):    Print(i)#Executes at each call to next (), encounters a yield statement return, and executes again from the yield statement that was last returned. #The execution process is probably as followsN = 1N= 1, 0N= 1, 1N= 1, 1, 0N= 1, 2, 1N= 1, 2, 1, 0N= 1, 3, 3, 1N= 1, 3, 3, 1, 0N= 1, 4, 6, 4, 1#................... .........

Add:

Methods to find out the type of a data

A = 1
Print (Type (a))
#<class ' int ' >

List generation review and builder exercises, Yang Hui triangle instances (very ingenious)

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.