conditional end call is met.def func (N): + = 1 # (1) func is 1,n is 2 (3) func is 2,n is 3 (5) func is 3,n is 4 if n >=4 : return ' End ' # (6) greater than or equal to 4 o'clock, return ' End ' return func (n) # (2) Here is 2 (4) Here is 3 r = func (1)print( R) # (7) Final return ' End 'Using recursion to achieve factorial:1*2*3*4*5*6*7def func (N): if or n==1: return 1 return n*func (n-1) # 7*func (6 then Func (6) is 6*func (5) and then always recur
offset in a non-exhaustive traversal, but not an element at offset if both the offset and offset elements are required, you can use the enumerate () function to return a generator object with this built-in function‘www.baidu.com‘>>> enumerate(url) #发现是个内存对象证明这个内置函数是一个生成器对象object at 0x000000000217D3A8>>>> g1 = enumerate(url)>>> g1.next()(0, ‘w‘)Generator function: The function body contains the yield keyword, and the result of the function is the generator function #生成器本身是迭代器#yield的功能: 1. Sim
) returns a 5-length data, and if it is a range (1000) it takes up a 1000-size array space, and if we use the ' generator ' to generate a number when needed, the space occupancy will be reduced. Here we can use the xrange () function to implement.Xrange Function Description: The usage is exactly the same as the range, and the difference is that it is not an array, but a generator. xrange example: "' >>> xrange (5) xrange (5) >>> list (xrange (5)) [0, 1, 2, 3, 4]>>> xrange (1,5) xrange ( 1, 5)
function contains the yield syntax, the function becomes the generatorCode:defCash_money (amount): whileAmount>0:amount-=100yield100#as long as yield is the generator, the value returned by the generator is an iterator Print("We 're taking the money again.") ATM=cash_money (500)Print(Type (ATM))Print(ATM.__next__())Print(ATM.__next__())Print('Other thing')#To build the benefits of iterators, the function executes half after the other work, and after the work is done, proceed with the fun
definition contains a yield keyword, then the function is no longer a normal function, but a generator:f = fib (a) Print F----------------Generator and functions do not have the same execution flow. The function is executed sequentially, the statement is encountered return or the last line of the function is returned. The function that becomes generator, executes at each invocation next() , encounters a yield statement return, and executes again from the last statement returned yield .python--l
( Let detail of map.values ()) { 8 Console.log (detail); 9 } 1 let set = new set ([Ten, 30 ] ); 2 for ( Let num of Set.keys ()) { 3 Console.log (num ); 4 5 6 let map = new map ([[' Name ', ' Ghostwu '], [' Age ', 22 7 for ( Let detail of Map.keys ()) { 8 Console.log ( detail); 9 } Default iterator:1Let userlist = [' Ghostwu ', ' Goku ', ' eight commandments ' ];2 3 //equivalent to calling values4 for(let name of UserList) {5 Console.log (name);6 }7 8Let set =NewSet
normal objects, and can be assigned to other variables, which can be used as return values and can be defined within another function.1 Import Time2 3 defTiming (fun):4 5 defDeco (*ARG, * *kwarg):6 7Start_time =time.time ()8 9Fun (*arg, * *Kwarg)Ten OneStop_time =time.time () A - Print('The func run time is:%s'% (Stop_time-start_time)) - the returndeco - - @Timing - defTar (name, age): + -Time.sleep (2) + A Print('In the tar:', name, age) at -Tar'HK', 18)Operation Res
" Run results, will appear fengzi111, because import test2, "test2.py" was executed once.Why can't I print the fengzi222?"test2.py" is introduced into the "test1.py". In "test2.py" there is the if judgment, the result of judgment: they are two not the same name.Look at the code print (test2.__name__) in the "test1.py" file, which deliberately shows what the name "test2.py" is. The result returned is test2, but now the "test1.py" file is executed! "Test1" = = "Test2"? Obviously false, then there
, tuple, dictionary, collection, file object) that these types of data must be an iterative object? But why do I define a list of a = [1, 2, 3, 4] without the A.next () method, punch the face?(strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, but in the for loop, they call their internal __iter__ method, turn them into an iterative object, and the For loop invokes the __next__ method of an iterative object to fetch the value, And the For loop catch
Generates a random numeric password of the specified lengthGenerates a random letter password of the specified lengthGenerates a mix of random numbers and letters of a specified length#encoding =utf-8Import RandomImport stringClass Password_generator:Password_time=0def __init__ (self,length):Self.length=lengthdef digital_password (self):Password_generator.password_time+=1S= ""For I in Range (self.length):S+=str (Random.randint (0,9))return s@classmethoddef letter_password (cls,length):Password_g
Personally feel that iterator and yield achieve the same function, but iterator need to implement in the class, yield is implemented in the real function, both will save the stateThe generator is also implemented by iterators#!/usr/bin/env python#coding:utf-8# definition three functions def Lee (name,age): Return ' I am%s,i am%d old '% (name,age) def Ma Rlon (): Return ' I am Marlon ' Def Allen (): Return ' I am Allen ' function_list= [Lee,marlon,allen] #有三个函数的列表 # definition A generator def myg
=fname5Self.max_sentence_length =Max_sentence_length6 7 def __iter__(self):8 #The entire corpus is one gigantic line--there be no sentence marks at all9 #So just split the sequence of tokens arbitrarily:1 sentence = tokensTenSentence, rest = [], b"' One With Utils.smart_open (self.fname) as Fin: A whileTrue: -Text = rest + fin.read (8192)#avoid loading the entire file (=1 line) into RAM - ifText = = Rest:#EOF theSentence.extend (Rest.split ())#re
is encountered.Invokes a generator function that returns an Iterator object.Compared with yield and not the caseYield execution ResultsNo yield execution resultsUnder what circumstances will yield be used?A function f,f returns a list, which is dynamically computed (either mathematically or logically, and the list is large (either fixed or enlarged with the increase in input parameters), and this is the time at which the It is useful to have a single list element instead of a complete list to s
] Traversal mode# [variable (processed variable) for variable in iteration object if judgment] Filter mode# L1 = [I for I in range (1, 101) if I% 2 = = 0]# Print (L1)#1, filter, all the odd numbers within 100. # L2 = [I for I in range (1, 101) if I% 2 = = 1]# L2 = [I for I in range (1, 101, 2)]# Print (L2)#2, the square of all the numbers within 10. [1,4,9,16 ... []# Print ([I*i for I in range (1, one)])#3, leave the number in the list that is divisible by three within 100. # Print ([i-I in rang
0Next (G)#Output 1Next (I1)#Output 4 #(2) The generator does not retain the result after the iterationGen = (i forIinchRange (4)) inchGen#returns TrueinchGen#returns TrueinchGen#return False, in fact, when detecting 2, 1 is not in the generator, that is, 1 has been iterated, the same 2, 3 is not2. Generator expressionsLimitations: only suitable for simple algorithmsExample: for in range (1,10))print(next Test)print(test). __next__())3. Generator function yieldExample of the Fibonacci func
One, List generation: 1, generate a list: lists = [i*2 for i in range] #使用列表生成式生成一个列表, occupy memory space, when the amount of large can cause a lot of waste. Print (list) 2, using the generator to generate the list: (generator) List1 = (i*2 for me in range) #将生成列表的公式存在变量中, take it when needed, (Note: The disadvantage is that you can only take the next one) print (list1.__next__ ()) #使用__next__取数据, take one number at a time and throw a stopiteration error at the end of the fetch fo
Always thought that Python generator is a list generation, OK, I read less. In fact, the generator is the generator object that implements the iterator protocol using yield returns. As follows: Class Data (object): def __init__ (self, *args): self._data = list (args) def __iter__ (self): for x in Self._data: yield x d = data () >>> d.__iter__ () Use D.next () in Python2 to return the next value of D,In Python3, you need to use Dnext() to return the next v
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.